Turtle in Python

Turtle

Turtle module in Python - the basic steps and methods.

It is important not to name your file turtle.py, as it will cause a conflict with Python's built-in turtle module. When you name your file turtle.py, Python tries to import your file instead of the actual turtle module, leading to an error. Always choose a unique name for your script, such as my_turtle_script.py.

Step 1: Import the turtle Module

You can write your code here. To use the turtle module, we need to import it at the beginning of our Python script:

import turtle

Step 2: Create a Turtle Object

We'll create a turtle object that we can use to draw on the screen:

t = turtle.Turtle()

When using the import turtle statement, you import the Turtle graphics module and can directly use its functions like turtle.write() to perform drawing operations. This approach is straightforward for simple scripts. However, by creating an instance of the Turtle class with t = turtle.Turtle(), you gain more control and flexibility. This allows you to create multiple turtle objects, each with their own attributes and methods, enabling them to operate independently. This is particularly beneficial in complex programs where you need multiple turtles to draw different parts of a scene simultaneously, manage individual turtle properties, or implement object-oriented programming principles to structure your code more efficiently.

By creating instances of the Turtle class, you can manage multiple turtles independently, each with unique attributes such as color and speed. For example, you can create two turtles, set their colors to different values, and control their movements separately:


import turtle

# Create the first turtle instance
t1 = turtle.Turtle()
t1.color("red")
t1.speed(1)
t1.forward(100)
t1.left(90)
t1.forward(100)

# Create the second turtle instance
t2 = turtle.Turtle()
t2.color("blue")
t2.speed(2)
t2.backward(100)
t2.right(90)
t2.forward(100)

# Create the third turtle instance
t3 = turtle.Turtle()
t3.color("green")
t3.speed(3)
t3.circle(50)

# Keep the window open
turtle.mainloop()

In this example:

  • The first turtle, t1, is red, moves forward 100 units, turns left, and moves forward another 100 units.
  • The second turtle, t2, is blue, moves backward 100 units, turns right, and moves forward 100 units.
  • The third turtle, t3, is green, and draws a circle with a radius of 50 units.

In the above example, we named the turtle instances t1, t2, and t3 to distinguish between them, but you can use any variable names you prefer. The names are simply identifiers for the turtle objects and do not affect their behavior or functionality. For instance, you could name them red_turtle, blue_turtle, and green_turtle to reflect their colors or any other meaningful names based on your specific use case.

This demonstrates how creating multiple turtle instances allows you to independently control their properties and actions, making it easier to create complex drawings and animations.

Step 3: Move the Turtle and set up your screen

To set up your screen in a turtle graphics program, you need to create a screen object and configure its properties. Use wn = turtle.Screen() to create the screen, wn.bgcolor('color') to set the background color, and wn.setup(width, height) to set the screen size. For example:
wn = turtle.Screen()
wn.bgcolor('pink')
wn.setup(200, 200)
To keep the screen open, use wn.mainloop() at the end of your script. Note that if you are using an online IDE, you might not be able to use these commands.

To use a picture as a background in your turtle graphics program, you can use the wn.bgpic('path_to_image') method. Make sure the image file is in the same directory as your script or provide the correct path to the image. For example:
wn = turtle.Screen()
wn.bgpic('background.gif')
Note that only GIF images are supported. Remember to use wn.mainloop() to keep the screen open.

In Python's Turtle graphics library, the turtle.title() function is used to set the title of the Turtle graphics window. This function takes a string as an argument, which specifies the title text to be displayed in the window's title bar.

Here's an example of how you can use turtle.title() to set a title for your Turtle graphics window:


# Set the title of the window turtle.title("My Turtle Graphics")

In this example, turtle.title("My Turtle Graphics") sets the title of the Turtle graphics window to "My Turtle Graphics". This title will be displayed in the title bar of the window while your Turtle graphics program is running.

The title set using turtle.title() is useful for identifying your Turtle graphics window and providing context for what the program is displaying or simulating.

We can move the turtle around the screen using various methods:

t.forward(distance)
Move the turtle forward by the specified distance in pixels.
   Example: t.forward(100) will move the turtle forward by 100 pixels.
t.backward(distance)
Move the turtle backward by the specified distance in pixels.
   Example: t.backward(50) will move the turtle backward by 50 pixels.
t.left(angle)
Turn the turtle left by the specified angle in degrees.
   Example: t.left(90) will turn the turtle 90 degrees to the left.
t.right(angle)
Turn the turtle right by the specified angle in degrees.
   Example: t.right(45) will turn the turtle 45 degrees to the right.
t.circle(radius)
Draw a circle with the specified radius.
   Example: t.circle(50) will draw a circle with a radius of 50 pixels.

Step 4: Customize the Turtle

We can customize the turtle's appearance and behavior using various methods:

t.color(color)
Set the colour of the turtle.
   Example: t.color('red') will set the turtle's colour to red.
  
Possible options
"black"
"white"
"red"
"blue"
"green"
"yellow"
"orange"
"purple"
"pink"
"brown"
"gray"
"cyan"
"magenta"
t.pensize(width)
Set the width of the turtle's pen.
   Example: t.pensize(3) will set the turtle's pen width to 3 pixels.
t.speed(speed)
Set the speed of the turtle's movement.
   Example: t.speed(2) will set the turtle's speed to a moderate pace.

Step 5: Adding Text

To add text to your turtle graphics program, you can use the turtle.write() method. It's a good practice to use variables to store your text and position values, as it makes your code easier to read and modify. For example:
message = "Hello, World!"
x = 0
y = 0
turtle.write(message, move=False, align="center", font=("Arial", 16, "normal"))

Using variables allows you to easily change the message or position without modifying multiple lines of code. Note that if you are using an online IDE, you might not be able to use these commands.

When using Python Turtle graphics, you can specify font families that are available on your system. Commonly supported fonts include sans-serif, serif, monospace, and cursive. These font families provide a range of styles suitable for different types of text. For instance, sans-serif fonts like Arial or Helvetica are clean and modern, serif fonts such as Times New Roman or Georgia have a more traditional appearance with embellished strokes, monospace fonts like Courier or Consolas ensure even spacing between characters, and cursive fonts like Comic Sans or Brush Script mimic handwriting for a decorative effect.

Examples of Font Families:
  • Sans-serif: Arial, Helvetica, Verdana
  • Serif: Times New Roman, Georgia, Palatino
  • Monospace: Courier, Consolas, Monaco
  • Cursive: Comic Sans MS, Brush Script, Lobster

In Python Turtle, when setting the font, you typically use a string to specify the font family, such as 'Arial', 'Times New Roman', 'Courier', or 'Comic Sans MS'. These fonts must be installed on your computer for Python to recognize and use them.

Step 6: Using Inputs in Python Turtle Graphics

In Python's Turtle graphics, inputs can include text inputs, such as asking users for shapes to draw, or direction inputs to control the turtle's movements. These inputs can be used dynamically to create interactive and versatile graphics.

For example, consider a scenario where you ask the user what shape they want to draw:

    import turtle

    # Function to draw a triangle

    def draw_triangle():

        turtle.forward(100)

        turtle.left(120)

    # Function to draw a square

    def draw_square():

        turtle.forward(100)

        turtle.left(90)

    # Ask user for input

    answer = turtle.textinput("Shape", "What shape do you want to draw? (triangle/square)")

    # Determine which function to call based on user's input

    if answer == "triangle":

        draw_triangle()

    elif answer == "square":

        draw_square()

    # Close the window when finished

    turtle.done()

Inputs can also control the turtle's movements. For instance, you can ask the user whether the turtle should go left or right:

    import turtle

    # Ask user for direction input

    direction = turtle.textinput("Direction", "Which direction do you want to go? (left/right)")

    # Move the turtle based on user's input

    if direction == "left":

        turtle.left(90)

        turtle.forward(100)

    elif direction == "right":

        turtle.right(90)

        turtle.forward(100)

    # Close the window when finished

    turtle.done()

Python Turtle also provides turtle.numinput() for numerical input. Here's an example where the user can specify the number of sides for a polygon:

    import turtle

    # Function to draw a polygon with given number of sides

    def draw_polygon(sides):

        angle = 360 / sides

        for _ in range(sides):

            turtle.forward(100)

            turtle.left(angle)

    # Ask user for number of sides using num input

    sides = turtle.numinput("Polygon Sides", "How many sides should the polygon have?", default=3, minval=3, maxval=10)

    if sides is not None:

        draw_polygon(int(sides))

    # Close the window when finished

    turtle.done()

These examples demonstrate the flexibility of using inputs in Python Turtle graphics to create interactive and dynamic drawings, where user input determines the actions and shapes drawn by the turtle.

Step 7: Using Keyboard and Mouse Events in Python Turtle Graphics

Python's Turtle graphics module allows children to interact with drawings using keyboard and mouse events. These events enable dynamic control over the turtle's movements and actions, making the learning experience engaging and interactive.

Here are the commands and their usage:

    turtle.onkey(function, key): Binds a function to a key press event.

       function: The function to call when the key is pressed.

       key: The key to bind the function to (e.g., 'Up', 'Down', 'Left', 'Right', 'a', 'b', etc.).

Example:

       turtle.onkey(turtle.forward, 'Up') - Moves the turtle forward when the 'Up' arrow key is pressed.

    turtle.listen(): Sets focus on the turtle window to capture events.

Example:

       turtle.listen() - Enables the turtle window to listen for events.

    turtle.onclick(function, btn): Binds a function to a mouse click event.

       function: The function to call when the mouse button is clicked.

       btn: The mouse button to bind the function to (e.g., 1 for left button, 2 for middle button, 3 for right button).

Example:

       turtle.onclick(turtle.goto, 1) - Moves the turtle to the clicked position using the left mouse button.

    turtle.onscreenclick(function, btn): Similar to turtle.onclick(), but coordinates are relative to the screen.

       function: The function to call when the mouse button is clicked.

       btn: The mouse button to bind the function to (e.g., 1 for left button, 2 for middle button, 3 for right button).

Example:

       turtle.onscreenclick(turtle.goto, 3) - Moves the turtle to the clicked position using the right mouse button, relative to the screen.

    turtle.onkeypress(function, key): Binds a function to a key press event, requires turtle.listen() to be called first.

       function: The function to call when the key is pressed.

       key: The key to bind the function to (e.g., 'a', 'b', 'Left', 'Right').

Example:

       turtle.onkeypress(turtle.left, 'Left') - Turns the turtle left when the 'Left' arrow key is pressed.

    turtle.onkeyrelease(function, key): Binds a function to a key release event, requires turtle.listen() to be called first.

       function: The function to call when the key is released.

       key: The key to bind the function to (e.g., 'a', 'b', 'Left', 'Right').

Example:

       turtle.onkeyrelease(turtle.stop, 'Up') - Stops the turtle when the 'Up' arrow key is released.

    turtle.onscreenkeypress(function, key): Similar to turtle.onkeypress(), but coordinates are relative to the screen.

Example:

       turtle.onscreenkeypress(turtle.right, 'Right') - Turns the turtle right when the 'Right' arrow key is pressed, relative to the screen.

    turtle.onscreenkeyrelease(function, key): Similar to turtle.onkeyrelease(), but coordinates are relative to the screen.

Example:

       turtle.onscreenkeyrelease(turtle.stop, 'Down') - Stops the turtle when the 'Down' arrow key is released, relative to the screen.

turtle.onclick() and turtle.onkeypress() can be combined to create more interactive programs where the turtle responds to both mouse clicks and keyboard presses.

These commands allow children to create interactive drawings and games using Python Turtle graphics, enhancing their understanding of programming concepts through hands-on activities.

Step 8: Example of Using Mouse and Keyboard Events in Python Turtle

This example shows how to use mouse and keyboard events in Python Turtle graphics. The turtle will move according to mouse clicks and keyboard presses.

import turtle

# Function to move the turtle to clicked position
def move_to_clicked(x, y):
    turtle.goto(x, y)

# Function to move turtle forward
def move_forward():
    turtle.forward(10)

# Function to move turtle backward
def move_backward():
    turtle.backward(10)

# Function to turn turtle left
def turn_left():
    turtle.left(10)

# Function to turn turtle right
def turn_right():
    turtle.right(10)

# Setup turtle screen
turtle.speed(0)  # Set turtle speed to maximum

# Bind mouse click events
turtle.onscreenclick(move_to_clicked, 1)  # Left click moves turtle to clicked position
turtle.onscreenclick(move_forward, 3)     # Right click moves turtle forward

# Bind keyboard events
turtle.listen()  # Set focus on turtle window to capture events
turtle.onkeypress(turn_left, 'Left')     # Left arrow key turns turtle left
turtle.onkeypress(turn_right, 'Right')   # Right arrow key turns turtle right
turtle.onkeypress(move_backward, 'Down') # Down arrow key moves turtle backward

# Instructions
print("Click left mouse button to move turtle to that position.")
print("Click right mouse button to move turtle forward.")
print("Use arrow keys to turn the turtle.")
print("Press 'Down' arrow key to move turtle backward.")
print("Click on the screen to interact with the turtle!")

turtle.mainloop()  # Keep the window open

In this example:

  • The turtle responds to left and right mouse clicks by moving to the clicked position or moving forward, respectively.
  • Keyboard events are used to turn the turtle left and right, and move the turtle backward.
  • The turtle's speed is set to maximum with turtle.speed(0).
  • Instructions are printed in the console to guide interaction with the turtle.

Step 9: Start creating your own turtle drawings

Now that you know the basic steps and methods, you can start creating your own turtle drawings! Use the turtle methods to move, turn, and draw shapes. Combine them in different ways to make beautiful and creative artwork!

Turtle graphics

The turtle module in Python provides a fun and interactive way to learn programming and create drawings. By following these steps and using the turtle methods, you can explore the world of turtle graphics and bring your ideas to life. Have fun and enjoy your turtle adventures!

Draw a House using Turtle

Draw the House

Let's draw the different parts of the house one by one:

# Draw the base of the house t.forward(100) t.left(90) t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)
# Move to the roof starting position
t.left(45)
t.forward(70)
t.left(90)
# Draw the roof
t.forward(70)
t.left(90)
t.forward(70)
t.left(45)
# Move to the door starting position
t.right(90)
t.forward(100)
t.left(90)
# Draw the door
t.forward(40)
t.left(90)
t.forward(20)
t.left(90)
t.forward(40)

Watch as the turtle draws a house

Run the program and watch as the turtle draws a house on the screen. You can customize the house by changing the turtle's colour, pen width, and speed. Experiment with different values and let your imagination run wild!

Create your own unique drawings

With the turtle module in Python, drawing a house becomes a fun and interactive experience. By following these steps and using the turtle methods, you can create your own unique houses or explore other shapes and designs. Have fun and enjoy your turtle drawing adventures!

Draw Shapes in Python

Draw Shapes using Loops

Let's draw different shapes using loops:

Draw a Square
# Set the side length of the square
side_length = 100
# Draw the square
for _ in range(4):
   t.forward(side_length)
   t.right(90)

Let's explore a simple code snippet in Python. In this code, we are using a loop to repeat a certain block of code four times.

The line of code for _ in range(4): is called a "for loop." It allows us to repeat a set of instructions a specific number of times.

Here's how the code works:

for _ in range(4):
    # Code to be repeated goes here

The for keyword is used to start the loop, followed by a variable name. In this case, we use an underscore (_) as the variable name, which is a common convention when we don't need to use the variable's value.

The range(4) function generates a sequence of numbers from 0 to 3 (four numbers in total). The loop then iterates over each number in this sequence.

Inside the loop, you can write any code that you want to repeat. It could be printing a message, drawing shapes, or performing calculations.

For example, let's say we want to print the numbers from 1 to 4. We can modify the code like this:

for i in range(1, 5):
    print(i)

When you run this code, it will display the numbers 1, 2, 3, and 4 on separate lines.

By using loops, we can save time and avoid duplicating code. We can perform repetitive tasks efficiently and make our programs more powerful.

Now that you understand how the for loop works, you can use it to create interesting patterns creating your own drawings!

Draw a Triangle
# Set the side length of the triangle
side_length = 100
# Draw the triangle
for _ in range(3):
   t.forward(side_length)
   t.right(120)
Draw a Pentagon
# Set the side length of the pentagon
side_length = 100
;# Draw the pentagon
for _ in range(5):
   t.forward(side_length)
   t.right(72)

Watch as the turtle draws different shapes on the screen

Run the program and watch as the turtle draws different shapes on the screen. You can customize the shapes by changing the side lengths, turtle's color, pen width, and speed. Experiment with different values and create your own unique designs!

Explore the world of shapes and patterns

Using loops in Python with the turtle module allows us to draw various shapes with ease. By following these steps and experimenting with different values, you can unleash your creativity and explore the world of shapes and patterns.

Draw Shapes in Python using Nested Lists

Draw Shapes

Let's draw shapes using nested lists and loops:

Draw a Square
# Set the side length of the square
side_length = 100
# Define the square coordinates
square = [[0, 0], [0, side_length], [side_length, side_length], [side_length, 0]]
# Draw the square
for i in range(len(square)):
   t.goto(square[i])

Let's understand a code snippet that uses the turtle module in Python to draw a square. graphics and draw shapes on the screen.

In this code, we define a list called "square" that contains the coordinates of the square's four corners. Each coordinate is represented as a pair of values, where the first value represents the x-coordinate and the second value represents the y-coordinate.

Here's how the code works:

square = [[0, 0], [0, side_length], [side_length, side_length], [side_length, 0]]

# Draw the square
for i in range(len(square)):
    t.goto(square[i])

First, we define the "square" list, which represents the square's corners. The "side_length" variable determines the length of the square's sides. You can choose any value you like.

The "for" loop is used to go through each corner in the "square" list. It helps us draw the square by repeating a set of instructions for each corner.

Inside the loop, we use the "goto()" method of the turtle module to move the turtle to each corner of the square. The "square[i]" part gives us the coordinates of the current corner from the "square" list.

When you run this code, it will draw a square on the screen using the turtle graphics. Each corner of the square will be connected by lines.

Using the turtle module, you can create various shapes, draw colorful patterns, and bring your imagination to life through art and animation. Have fun exploring and creating with the turtle!

Draw a Triangle
# Set the side length of the triangle
side_length = 100
# Define the triangle coordinates
triangle = [[0, 0], [side_length/2, side_length], [side_length, 0]]
# Draw the triangle
for i in range(len(triangle)):
   t.goto(triangle[i])
Draw a Pentagon
# Set the side length of the pentagon
side_length = 100
# Define the pentagon coordinates
pentagon = [[0, 0], [side_length, 0], [side_length + side_length/2, side_length], [side_length/2, side_length], [0, 0]]
# Draw the pentagon
for i in range(len(pentagon)):
   t.goto(pentagon[i])

Customize the shapes

Run the program and watch as the turtle draws different shapes on the screen. You can customize the shapes by changing the coordinates, side lengths, turtle's color, pen width, and speed. Experiment with different values and create your own unique designs!

Python Turtle Methods

t.forward(distance)

Move the turtle forward by the specified distance.
Arguments: distance (number) - The distance to move forward.
Example: t.forward(100) will move the turtle forward by 100 units.
Possible values: Any positive or negative number.
Learn more: Python Turtle - forward()

t.right(angle)

Turn the turtle clockwise by the specified angle.
Arguments: angle (number) - The angle to turn clockwise in degrees.
Example: t.right(90) will turn the turtle 90 degrees to the right.
Possible values: Any number representing the angle in degrees.
Learn more: Python Turtle - right()

t.circle(radius, extent=None)

Draw a circle with the specified radius and extent (optional).
Arguments: radius (number) - The radius of the circle, extent (number or None) - The angle of the circle in degrees. If None, draw a full circle.
Example: t.circle(50) will draw a circle with a radius of 50 units.
Possible values: Radius - Any positive number, Extent - Any number representing the angle in degrees or None.
Learn more: Python Turtle - circle()

t.backward(distance)

Move the turtle backward by the specified distance.
Arguments: distance (number) - The distance to move backward.
Example: t.backward(50) will move the turtle backward by 50 units.
Possible values: Any positive or negative number.
Learn more: Python Turtle - backward()

t.left(angle)

Turn the turtle counterclockwise by the specified angle.
Arguments: angle (number) - The angle to turn counterclockwise in degrees.
Example: t.left(45) will turn the turtle 45 degrees to the left.
Possible values: Any number representing the angle in degrees.
Learn more: Python Turtle - left()

t.goto(x, y=None)

Move the turtle to the specified coordinates.
Arguments: x (number) - The x-coordinate, y (number or None) - The y-coordinate. If None, move to the current y-coordinate.
Example: t.goto(100, 100) will move the turtle to the point (100, 100) on the screen.
Possible values: x - Any number, y - Any number or None.
Learn more: Python Turtle - goto()

t.penup()

Lift the turtle's pen off the screen, so it won't draw while moving.
Example: t.penup() will lift the turtle's pen off the screen.
Learn more: Python Turtle - penup()

t.pendown()

Put the turtle's pen back on the screen, so it can start drawing again.
Example: t.pendown() will put the turtle's pen back on the screen.
Learn more: Python Turtle - pendown()

t.speed(speed=None)

Set the speed of the turtle's movements.
Arguments: speed (integer or None) - The speed of the turtle. Values range from 0 (slowest) to 10 (fastest). If None, return the current speed.
Example: t.speed(3) will set the turtle's speed to a medium pace.
Possible values: Integer values from 0 to 10, or None.
Learn more: Python Turtle - speed()

t.dot(size=None, color=None)

Draw a dot at the turtle's current position.
Arguments: size (number or None) - The size of the dot. If None, use the default size. colour (string or None) - The colour of the dot. If None, use the default color.
Example: t.dot(10, 'red') will draw a red dot with a size of 10 units.
Possible values: size - Any positive number or None, colour - Any valid colour string or None.
Learn more: Python Turtle - dot()

t.setheading(to_angle)

Set the turtle's heading (angle) to the specified value.
Arguments: to_angle (number) - The angle to set the turtle's heading to, measured in degrees.
Example: t.setheading(90) will set the turtle's heading to 90 degrees (facing north).
Possible values: Any number representing the angle in degrees.
Learn more: Python Turtle - setheading()

t.home()

Move the turtle to the home position (0, 0) and set its heading to its initial value (usually east).
Example: t.home() will move the turtle to the home position and reset its heading.
Learn more: Python Turtle - home()

t.clear()

Clear the turtle's drawings and return its state to the starting position.
Example: t.clear() will clear the turtle's drawings and reset its position and heading.
Learn more: Python Turtle - clear()

t.fillcolor(color)

Set the fill colour for the turtle's shape.
Arguments: colour (string) - The colour to set as the fill color.
Example: t.fillcolor('blue') will set the turtle's shape fill colour to blue.
Possible values: Any valid colour string.
Learn more: Python Turtle - fillcolor()

t.begin_fill()

Begin filling the area drawn by the turtle's movements.
Example: t.begin_fill() will start filling the area inside the shape drawn by the turtle.
Learn more: Python Turtle - begin_fill()

t.end_fill()

Stop filling the area drawn by the turtle's movements and complete the shape.
Example: t.end_fill() will stop filling the area inside the shape drawn by the turtle and complete the shape.
Learn more: Python Turtle - end_fill()

t.write(arg, move=False, align="left", font=("Arial", 8, "normal"))

Write text at the turtle's current position.
Arguments: arg (any) - The text to write, move (bool) - Whether to move the turtle after writing, align (string) - The alignment of the text ("left", "center", "right"), font (tuple) - The font settings for the text.
Example: t.write("Hello!", True, "center", ("Arial", 12, "bold")) will write the text "Hello!" at the turtle's current position, move the turtle, center-align the text, and use the Arial font with size 12 and bold style.
Possible values: arg - Any text or variable, move - True or False, align - "left", "center", or "right", font - A tuple with the font family, size, and style.
Learn more: Python Turtle - write()

t.stamp()

Stamp a copy of the turtle's shape onto the screen.
Example: t.stamp() will stamp a copy of the turtle's shape onto the screen at its current position.
Learn more: Python Turtle - stamp()

t.hideturtle()

Hide the turtle's shape on the screen.
Example: t.hideturtle() will hide the turtle's shape on the screen.
Learn more: Python Turtle - hideturtle()

t.showturtle()

Show the turtle's shape on the screen.
Example: t.showturtle() will show the turtle's shape on the screen if it was previously hidden.
Learn more: Python Turtle - showturtle()