Python - Turtle

The turtle module provides a visual and intuitive way to introduce programming concepts through a simple, interactive graphics interface.

Introduction

The turtle module is a classic and effective way to introduce programming concepts through interactive graphics. It provides immediate visual feedback, making it ideal for beginners to explore how software works.

Originally developed as an educational tool for the classroom, turtle graphics offers a simple way to generate graphical output without the complexity of external libraries. Whether you’re teaching programming to children or just need a quick way to draw something on the screen, turtle is a joy to use due to its minimal overhead and intuitive commands.

Getting started

The turtle module exposes its basic functionality as a set of functions.

Start a new interactive Python session:

Terminal window
uv run python

Basic drawing

Imagine a robotic turtle starting at the center of the screen (position (0, 0) in the x-y plane).

Import all the objects from the turtle module:

from turtle import *

Send the turtle forward 100 steps:

forward(100)

You should see a new window appear on your display with a line drawn by the turtle, heading East.

Next, we can change the direction of the turtle. Let’s make it turn 120 degrees to the left (counter-clockwise):

left(120)

Now, let’s complete a triangle by moving forward and turning again:

forward(100)
left(120)
forward(100)

Notice how the turtle, represented by an arrow, points in different directions as you steer it. Experiment with these commands, and also try backward() and right().

Pen control

You can change the appearance of the lines the turtle draws. For example, to change the color to blue and the line width to 3:

color('blue')
width(3)

You can also move the turtle around without drawing by lifting the pen with up(). When you’re ready to start drawing again, use down().

The turtle’s position

If your turtle has disappeared off-screen, or you want to start over, you can send it back to its starting point:

home()

The home position is at the center of the screen (0, 0). If you need to know the turtle’s current coordinates, use pos():

print(pos())

Close the interactive session by pressing Ctrl+D.

Making algorithmic patterns

Using loops, you can build intricate geometric patterns with very little code:

pattern.py
from turtle import *
for steps in range(100):
for c in ('blue', 'red', 'green'):
color(c)
forward(steps)
right(30)
mainloop()

Note that the mainloop() command is required to keep the turtle window open.

These patterns are limited only by your imagination!

Let’s draw a star shape. We’ll use red lines filled with yellow:

color('red')
fillcolor('yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()

The abs(pos()) < 1 condition is a neat way to check when the turtle has returned to its starting point.

Note that the filling only actually takes place once you call the end_fill() command.

Functions

Following some exploratory messing around, a common first Turtle activity is to draw a geometric shape.

How about a square?

square.py
from turtle import *
forward(50)
right(90)
forward(50)
right(90)
forward(50)
right(90)
forward(50)
right(90)
mainloop()

Using the range() function you can repeat code a specific number of times to draw a square:

for i in range(4):
forward(50)
right(90)

Another important aspect of Python is defining new functions.

So we add a new “word”, square, to our script:

def square():
for i in range(4):
forward(50)
right(90)
square()

Now if we type square, Python draws a square just as if we had typed for i in range(4): ....

Python has learned a new word.

Now that square is in Pythons’s vocabulary, the new word may be used as part of another instruction.

For example:

for i in range(36):
right(10)
square()

We can give this a name also:

def flower():
for i in range(36):
right(10)
square()
flower()

Programming is done by adding new words to the existing vocabulary. It’s like learning a spoken language. New words are defined using words you already know.

Things can get more complex. Functions can take “inputs” so that the information they use varies.

We could write a square function like this:

def square(size: int = 50):
for i in range(4):
forward(size)
right(90)

Instead of always having a square of 50 units on a side we can tell it how big to be:

square(100)

There’s more:

def spiral(size: int = 0, angle: int = 90):
if size > 100:
return
forward(size)
right(angle)
spiral(size + 2, angle)
spiral(0, 91)

Geometry

The traditional Euclidean geometry is built on abstractions: a point that has no size; a line that has length but no thickness. This is difficult for young learners to grasp. The turtle is a real concrete object that may be seen and manipulated. Analytic geometry rests on an outside frame of reference — the coordinate system. In contrast, turtle geometry is “body syntonic”. The turtle moves around as you do. You can identify with it and understand what it is doing.

Turtle geometry was not intended to be a replacement for traditional geometry but rather, as an alternative entry point into geometry and mathematics in general. It is appropriate for young children as well as adults.

The rationale behind turtle geometry is thoroughly explained by Seymour Papert in Mindstorms . Many versions of Logo come with tutorials and guide books about turtle geometry.

While it is easy to get started with turtle geometry, it can also get quite complex. The book Turtle Geometry, by Hal Abelson and Adrea diSessa includes many advanced explorations with the turtle.

Object-oriented

While the examples above use global functions (via from turtle import *), you can also use an object-oriented approach by creating specific Turtle instances. This is especially useful if you want to have multiple turtles on the screen at the same time.

In this approach, the various turtle commands are methods associated with objects (mostly of Turtle objects).

object.py
from turtle import Turtle
from random import random
t = Turtle()
t.shape("turtle")
for i in range(100):
steps = int(random() * 100)
angle = int(random() * 360)
t.right(angle)
t.fd(steps)
t.screen.mainloop()

Note the last line. t.screen is an instance of the Screen that a Turtle instance exists on; it’s created automatically along with the turtle.

The turtle’s screen can be customized, for example:

t.screen.title('Object-oriented turtle demo')
t.screen.bgcolor("orange")

👉 The Beginner’s Guide to Python Turtle (Real Python)

Key

Key Presses & Events

game.py
import turtle
tim = turtle.Turtle()
def up():
tim.setheading(90)
tim.forward(100)
def down():
tim.setheading(270)
tim.forward(100)
def left():
tim.setheading(180)
tim.forward(100)
def right():
tim.setheading(0)
tim.forward(100)
turtle.onkey(up, "Up") # This will call the up function if the "Up" arrow key is pressed
turtle.onkey(down, "Down")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.listen()
turtle.mainloop()

Turtle icon

Instead of always using a turtle, you can tell the Python Turtle icon to use a different image. The image should be small, so that it does not cover up too much of the screen: 50 × 50 pixels will give you a large icon.

First you need to register the image with the screen:

screen = turtle.Screen()
screen.register_shape('happy.png')

Then you can set the shape:

turtle.shape('happy.png')

Turtle icons face right to start with. You can change the heading to get your image to face upwards:

turtle.setheading(90) # face upwards

Reference