Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 149 ยท Beyond the Basics

Turtle Graphics

Learn Python's turtle module. Move, turn and draw shapes with loops, use colors and fills, handle key presses, and try the ideas live with a plotting stand-in.

Imagine a robot with a pen taped to its belly. You tell it "walk 100 steps", "turn left 90 degrees", "walk 100 steps again", and a line appears behind it. After four such pairs you have a square. That is the whole idea of turtle graphics, and it has been used to teach programming since the 1960s because the results are visible immediately: a bug in your loop is a crooked drawing, not a mysterious number.

Python includes this robot in the standard library as the turtle module. In this lesson you will move and turn the turtle, draw polygons and spirals with loops, add colors and filled shapes, react to the keyboard, and learn the geometry that makes it all work. You'll also write a tiny turtle of your own that runs right here in the browser.

What runs here and what doesn't. The real turtle module is built on tkinter and needs a screen, so it can't run in the in-browser editors. The turtle code in this lesson is shown read-only: save it as a .py file and run it on your computer. The live examples use MiniTurtle, a small stand-in with the same method names that draws with matplotlib, so you can experiment with the same ideas without installing anything.

Your first drawing

Save this as square.py and run it:

Python
import turtle

t = turtle.Turtle()      # create a turtle; a window opens
t.forward(100)           # walk 100 steps
t.left(90)               # turn 90 degrees to the left
t.forward(100)
t.left(90)
t.forward(100)
t.left(90)
t.forward(100)

turtle.done()            # keep the window open until it is closed

The turtle starts in the middle of the window, facing right, with its pen down. forward(distance) moves in the direction it faces, left(angle) and right(angle) rotate it in place (angles are in degrees by default), and backward(distance) walks the other way. The short names fd, bk, lt and rt do the same.

Those eight lines repeat the same pair of instructions four times. Whenever you see repetition, use a loop:

Python
import turtle

t = turtle.Turtle()
for _ in range(4):
    t.forward(100)
    t.left(90)
turtle.done()

turtle.done() (also written turtle.mainloop()) starts the same kind of event loop that tkinter uses. Without it, the program ends and the window vanishes immediately. turtle.exitonclick() is a friendly variant that closes the window when you click it.

Coordinates and headings

The turtle always has two pieces of state besides the pen: a position and a heading. The window is a coordinate plane with (0, 0) in the center, x growing to the right and y growing up (the opposite of most screen coordinates). The heading is an angle: 0 means east, 90 means north, 180 west and 270 south, so angles grow counterclockwise.

Method Meaning
t.position() or t.pos() current (x, y)
t.heading() current angle in degrees
t.goto(x, y) move to a point (draws a line if the pen is down)
t.setheading(angle) face a compass-style direction
t.home() go to (0, 0) and face east
t.penup() / t.pendown() lift or lower the pen (up()/down() also work)

To move without drawing, lift the pen first: t.penup(), t.goto(-150, 80), t.pendown(). Forgetting pendown() afterwards is the most common "why is nothing drawn?" bug.

Under the hood, forward(d) is just trigonometry. If the heading is h degrees, the new position is x + d * cos(h) and y + d * sin(h). This live example performs those calculations by hand to trace the square, with no drawing at all:

Python How forward() and left() work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the tiny rounding errors such as -0.0 or 100.0: cosines of 90 degrees are not exactly zero in floating point. The real turtle hides this by rounding for display. After four sides the turtle is back at the start, facing east again, because four turns of 90 degrees add up to a full 360.

Polygons: the turning rule

Why did the square use 90? Because the turtle must turn a total of 360 degrees to come back to its starting direction. For a polygon with n equal sides, each turn is 360 / n:

Python
import turtle

def polygon(t: turtle.Turtle, sides: int, length: int) -> None:
    for _ in range(sides):
        t.forward(length)
        t.left(360 / sides)

t = turtle.Turtle()
polygon(t, 3, 120)      # triangle
polygon(t, 6, 60)       # hexagon
polygon(t, 36, 10)      # almost a circle
turtle.done()

Wrapping the loop in a function with parameters turns one drawing into a family of drawings. The 36-sided polygon is a good reminder that a circle is just a polygon with many tiny sides; the built-in t.circle(radius) does this for you, and t.circle(radius, extent) draws only an arc of extent degrees.

The same turning rule explains stars. Turning by 144 degrees instead of 72 after each of five sides draws a five-pointed star, because the turtle winds around twice (2 x 360 = 720 = 5 x 144). Spirals come from changing the length on every step:

Python
import turtle

t = turtle.Turtle()
t.speed(0)                           # fastest animation
for step in range(120):
    t.forward(step * 3)              # longer every time
    t.left(91)                       # a little more than 90 degrees
turtle.done()

Try 89, 91 and 120 as the turn angle and watch the pattern change completely. Small numeric changes with big visual effects are what make turtle graphics fun to explore.

Pen, color and fill

The pen has a size and a color; closed shapes can be filled:

Python
import turtle

screen = turtle.Screen()
screen.bgcolor("midnight blue")
screen.title("Flower")

t = turtle.Turtle()
t.speed(0)
t.pensize(2)
t.color("gold", "orange")            # (pen color, fill color)

t.begin_fill()
for _ in range(36):
    t.circle(60, 60)                 # a petal arc
    t.left(120)
    t.circle(60, 60)
    t.left(130)
t.end_fill()

t.hideturtle()                       # hide the arrow cursor when done
screen.exitonclick()
  • color(pen, fill) sets both colors at once; pencolor() and fillcolor() set them individually. Colors can be names ("red"), hex strings ("#ff8800"), or RGB tuples ((1.0, 0.5, 0.0) by default, or 0 to 255 after screen.colormode(255)).
  • Everything drawn between begin_fill() and end_fill() is filled when end_fill() runs.
  • t.dot(size, color) stamps a round dot, t.write("Hello", font=("Arial", 16, "bold")) draws text, and t.shape("turtle") changes the cursor to a little turtle.
  • t.speed() takes 1 (slow) to 10 (fast), or 0 for "no animation delay". Even faster: call screen.tracer(0) to stop animating, draw everything, then call screen.update() once.

Many turtles and the keyboard

You can create several turtles; each has its own position, heading and pen. A screen also reacts to keys and clicks, which turns a drawing into a small interactive program:

Python
import turtle

screen = turtle.Screen()
t = turtle.Turtle()
t.shape("turtle")

def go_forward() -> None:
    t.forward(20)

def turn_left() -> None:
    t.left(15)

def turn_right() -> None:
    t.right(15)

def clear_drawing() -> None:
    t.clear()

screen.onkey(go_forward, "Up")       # call the function, not go_forward()
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")
screen.onkey(clear_drawing, "c")
screen.onscreenclick(lambda x, y: t.goto(x, y))
screen.listen()                      # without listen(), key presses are ignored
screen.mainloop()

Just like with tkinter buttons, you pass the function itself to onkey, and you need listen() so the window has keyboard focus. For animation, use screen.ontimer(function, milliseconds) and have the function re-schedule itself; avoid time.sleep(), which freezes the window.

Try it: a turtle you can run here

Because the real module can't open a window in the browser, here is MiniTurtle: a handful of lines that record every line the pen draws and then plot them with matplotlib. It uses the same turning rule and the same method names, so a function written for it also works with turtle.Turtle().

Python MiniTurtle: draw shapes with the turning rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The flower-like picture comes from six identical hexagons, each rotated by 60 degrees. Change polygon(t, 6, 60) to polygon(t, 5, 70) or add more colors, and notice that the turtle always ends exactly where it started: the printed end position is (0.0, 0.0) (possibly with a - sign from floating-point noise). Now a spiral, using the same stand-in with a different function:

Python Spirals from one changing length

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A turn just below or just above 90 degrees makes a square spiral that slowly twists one way or the other, while 120 degrees draws triangles that keep growing. The code is the same; only one number changed.

Common mistakes

  • The window flashes and disappears. The program ended. Finish with turtle.done() or screen.exitonclick().
  • turtle.py in your folder. Never name your own file turtle.py: Python would import your file instead of the standard module, and you get strange errors such as "module 'turtle' has no attribute 'Turtle'".
  • Nothing is drawn. Check that the pen is down (pendown()), and that you aren't using hideturtle() as a substitute for penup(): hiding the turtle does not lift the pen.
  • Closing the window and running again raises turtle.Terminator. The module keeps global state; restart the program rather than re-running turtle code from the same interpreter session.
  • Slow drawings. Use speed(0) or tracer(0) plus a final update() for anything with thousands of steps.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A turtle starts facing east. After forward(100) and left(90), which direction does it face?

    Angles grow counterclockwise and 90 degrees is north. A left turn adds to the heading, so the turtle now faces north.
  2. 2. How much should the turtle turn after each side to draw a regular octagon?

    The turns must add up to 360 degrees in total, so each of the 8 turns is 360 / 8 = 45 degrees.
  3. 3. Your script draws everything correctly, but the window closes instantly. What is missing?

    The program exits when it reaches the end. done() runs the event loop that keeps the window open and responsive.
  4. 4. What does the following do? t.penup(); t.goto(50, 50); t.pendown()

    Moving with the pen up leaves no line. pendown() then makes the following moves visible again.
  5. 5. Why should you never name your own program turtle.py?

    Python searches the script's own folder first, so import turtle would load your file and the real module would be hidden.

Summary

  • The turtle module draws by moving a pen-carrying turtle: forward(), backward(), left(), right(), goto(), with penup() and pendown() controlling whether lines appear.
  • The turtle has a position and a heading; 0 degrees is east and angles grow counterclockwise.
  • A regular polygon with n sides turns 360 / n degrees at each corner; stars and spirals come from different turn angles and changing lengths.
  • Use color(), pensize(), begin_fill() and end_fill() for style, and speed(0) or tracer(0) for fast drawings.
  • onkey(), onscreenclick() and ontimer() make interactive programs; always call listen() for keys and finish with done().
  • Real turtle code needs a screen. A stand-in such as MiniTurtle lets you practice the geometry anywhere.

Next: Python GUI Frameworks, a tour of the toolkits you can pick when tkinter is not enough.