from turtle import *
If you run into a No module named '_tkinter'
error, you’ll have to
install the Tk interface package
on your system.
Basic drawing
Send the turtle forward 100 steps:
forward(100)
You should see (most likely, in a new window on your display) a line
drawn by the turtle, heading East. Change the direction of the turtle,
so that it turns 120 degrees left (anti-clockwise):
left(120)
Let’s continue by drawing a triangle:
forward(100)
left(120)
forward(100)
Notice how the turtle, represented by an arrow, points in different
directions as you steer it.
Experiment with those commands, and also with backward()
and
right()
.
Pen control
Try changing the color - for example, color('blue')
- and
width of the line - for example, width(3)
- and then drawing again.
You can also move the turtle around without drawing, by lifting up the pen:
up()
before moving. To start drawing again, use down()
.
The turtle’s position
Send your turtle back to its starting-point (useful if it has disappeared
off-screen):
home()
The home position is at the center of the turtle’s screen. If you ever need to
know them, get the turtle’s x-y coordinates with:
pos()
Home is at (0, 0)
.
And after a while, it will probably help to clear the window so we can start
anew:
clearscreen()
Making algorithmic patterns
Using loops, it’s possible to build up geometric patterns:
for steps in range(100):
for c in ('blue', 'red', 'green'):
color(c)
forward(steps)
right(30)
- which of course, are limited only by the imagination!
Let’s draw the star shape at the top of this page. We want red lines,
filled in with yellow:
color('red')
fillcolor('yellow')
Just as up()
and down()
determine whether lines will be drawn,
filling can be turned on and off:
begin_fill()
Next we’ll create a loop:
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
abs(pos()) < 1
is a good way to know when the turtle is back at its
home position.
Finally, complete the filling:
end_fill()
(Note that filling only actually takes place when you give the
end_fill()
command.)
How to…
This section covers some typical turtle use-cases and approaches.
Get started as quickly as possible
One of the joys of turtle graphics is the immediate, visual feedback that’s
available from simple commands - it’s an excellent way to introduce children
to programming ideas, with a minimum of overhead (not just children, of
course).
The turtle module makes this possible by exposing all its basic functionality
as functions, available with from turtle import *
. The turtle
graphics tutorial covers this approach.
It’s worth noting that many of the turtle commands also have even more terse
equivalents, such as fd()
for forward()
. These are especially
useful when working with learners for whom typing is not a skill.
You’ll need to have the Tk interface package
installed on
your system for turtle graphics to work. Be warned that this is not
always straightforward, so check this in advance if you’re planning to
use turtle graphics with a learner.
Use the turtle
module namespace
Using from
turtle import *
is convenient - but be warned that it imports a
rather large collection of objects, and if you’re doing anything but turtle
graphics you run the risk of a name conflict (this becomes even more an issue
if you’re using turtle graphics in a script where other modules might be
imported).
The solution is to use import turtle
- fd()
becomes
turtle.fd()
, width()
becomes turtle.width()
and so on. (If typing
“turtle” over and over again becomes tedious, use for example import turtle
as t
instead.)
Use turtle graphics in a script
It’s recommended to use the turtle
module namespace as described
immediately above, for example:
import turtle as t
from random import random
for i in range(100):
steps = int(random() * 100)
angle = int(random() * 360)
t.right(angle)
t.fd(steps)
Another step is also required though - as soon as the script ends, Python
will also close the turtle’s window. Add:
t.mainloop()
to the end of the script. The script will now wait to be dismissed and
will not exit until it is terminated, for example by closing the turtle
graphics window.
Use object-oriented turtle graphics
See also
Explanation of the object-oriented interface
Other than for very basic introductory purposes, or for trying things out
as quickly as possible, it’s more usual and much more powerful to use the
object-oriented approach to turtle graphics. For example, this allows
multiple turtles on screen at once.
In this approach, the various turtle commands are methods of objects (mostly of
Turtle
objects). You can use the object-oriented approach in the shell,
but it would be more typical in a Python script.
The example above then becomes:
from turtle import Turtle
from random import random
t = 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 customised, for example:
t.screen.title('Object-oriented turtle demo')
t.screen.bgcolor("orange")
In the following documentation the argument list for functions is given.
Methods, of course, have the additional first argument self which is
omitted here.
Turtle methods
Turtle motion
- Move and draw
- Tell Turtle’s state
- Setting and measurement
Methods of RawTurtle/Turtle and corresponding functions
Most of the examples in this section refer to a Turtle instance called
turtle
.
Turtle motion
turtle.forward(distance)
turtle.fd(distance)
- Parameters:
distance – a number (integer or float)
Move the turtle forward by the specified distance, in the direction the
turtle is headed.
>>> turtle.position()
(0.00,0.00)
>>> turtle.forward(25)
>>> turtle.position()
(25.00,0.00)
>>> turtle.forward(-75)
>>> turtle.position()
(-50.00,0.00)
Move the turtle backward by distance, opposite to the direction the
turtle is headed. Do not change the turtle’s heading.
>>> turtle.position()
(0.00,0.00)
>>> turtle.backward(30)
>>> turtle.position()
(-30.00,0.00)
Turn turtle right by angle units. (Units are by default degrees, but
can be set via the degrees()
and radians()
functions.) Angle
orientation depends on the turtle mode, see mode()
.
>>> turtle.heading()
>>> turtle.right(45)
>>> turtle.heading()
337.0
Turn turtle left by angle units. (Units are by default degrees, but
can be set via the degrees()
and radians()
functions.) Angle
orientation depends on the turtle mode, see mode()
.
>>> turtle.heading()
>>> turtle.left(45)
>>> turtle.heading()
If y is None
, x must be a pair of coordinates or a Vec2D
(e.g. as returned by pos()
).
Move turtle to an absolute position. If the pen is down, draw line. Do
not change the turtle’s orientation.
>>> tp = turtle.pos()
(0.00,0.00)
>>> turtle.setpos(60,30)
>>> turtle.pos()
(60.00,30.00)
>>> turtle.setpos((20,80))
>>> turtle.pos()
(20.00,80.00)
>>> turtle.setpos(tp)
>>> turtle.pos()
(0.00,0.00)
Move turtle to an absolute position. Unlike goto(x, y), a line will not
be drawn. The turtle’s orientation does not change. If currently
filling, the polygon(s) teleported from will be filled after leaving,
and filling will begin again after teleporting. This can be disabled
with fill_gap=True, which makes the imaginary line traveled during
teleporting act as a fill barrier like in goto(x, y).
>>> tp = turtle.pos()
(0.00,0.00)
>>> turtle.teleport(60)
>>> turtle.pos()
(60.00,0.00)
>>> turtle.teleport(y=10)
>>> turtle.pos()
(60.00,10.00)
>>> turtle.teleport(20, 30)
>>> turtle.pos()
(20.00,30.00)
Added in version 3.12.
Set the turtle’s first coordinate to x, leave second coordinate
unchanged.
>>> turtle.position()
(0.00,240.00)
>>> turtle.setx(10)
>>> turtle.position()
(10.00,240.00)
Set the turtle’s second coordinate to y, leave first coordinate unchanged.
>>> turtle.position()
(0.00,40.00)
>>> turtle.sety(-10)
>>> turtle.position()
(0.00,-10.00)
Set the orientation of the turtle to to_angle. Here are some common
directions in degrees:
standard mode
logo mode
0 - east
0 - north
90 - north
90 - east
180 - west
180 - south
270 - south
270 - west
>>> turtle.setheading(90)
>>> turtle.heading()
turtle.home()
Move turtle to the origin – coordinates (0,0) – and set its heading to
its start-orientation (which depends on the mode, see mode()
).
>>> turtle.heading()
>>> turtle.position()
(0.00,-10.00)
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
Draw a circle with given radius. The center is radius units left of
the turtle; extent – an angle – determines which part of the circle
is drawn. If extent is not given, draw the entire circle. If extent
is not a full circle, one endpoint of the arc is the current pen
position. Draw the arc in counterclockwise direction if radius is
positive, otherwise in clockwise direction. Finally the direction of the
turtle is changed by the amount of extent.
As the circle is approximated by an inscribed regular polygon, steps
determines the number of steps to use. If not given, it will be
calculated automatically. May be used to draw regular polygons.
>>> turtle.home()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
>>> turtle.circle(50)
>>> turtle.position()
(-0.00,0.00)
>>> turtle.heading()
>>> turtle.circle(120, 180) # draw a semicircle
>>> turtle.position()
(0.00,240.00)
>>> turtle.heading()
180.0
Draw a circular dot with diameter size, using color. If size is
not given, the maximum of pensize+4 and 2*pensize is used.
>>> turtle.home()
>>> turtle.dot()
>>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
>>> turtle.position()
(100.00,-0.00)
>>> turtle.heading()
turtle.stamp()
Stamp a copy of the turtle shape onto the canvas at the current turtle
position. Return a stamp_id for that stamp, which can be used to delete
it by calling clearstamp(stamp_id)
.
>>> turtle.color("blue")
>>> stamp_id = turtle.stamp()
>>> turtle.fd(50)
Delete all or first/last n of turtle’s stamps. If n is None
, delete
all stamps, if n > 0 delete first n stamps, else if n < 0 delete
last n stamps.
>>> for i in range(8):
... unused_stamp_id = turtle.stamp()
... turtle.fd(30)
>>> turtle.clearstamps(2)
>>> turtle.clearstamps(-2)
>>> turtle.clearstamps()
turtle.undo()
Undo (repeatedly) the last turtle action(s). Number of available
undo actions is determined by the size of the undobuffer.
>>> for i in range(4):
... turtle.fd(50); turtle.lt(80)
>>> for i in range(8):
... turtle.undo()
Set the turtle’s speed to an integer value in the range 0..10. If no
argument is given, return current speed.
If input is a number greater than 10 or smaller than 0.5, speed is set
to 0. Speedstrings are mapped to speedvalues as follows:
“fastest”: 0
“fast”: 10
“normal”: 6
“slow”: 3
“slowest”: 1
Speeds from 1 to 10 enforce increasingly faster animation of line drawing
and turtle turning.
Attention: speed = 0 means that no animation takes
place. forward/back makes turtle jump and likewise left/right make the
turtle turn instantly.
>>> turtle.speed()
>>> turtle.speed('normal')
>>> turtle.speed()
>>> turtle.speed(9)
>>> turtle.speed()
turtle.pos()
Return the turtle’s current location (x,y) (as a Vec2D
vector).
>>> turtle.pos()
(440.00,-0.00)
Return the angle between the line from turtle position to position specified
by (x,y), the vector or the other turtle. This depends on the turtle’s start
orientation which depends on the mode - “standard”/”world” or “logo”.
>>> turtle.goto(10, 10)
>>> turtle.towards(0,0)
225.0
turtle.heading()
Return the turtle’s current heading (value depends on the turtle mode, see
mode()
).
>>> turtle.home()
>>> turtle.left(67)
>>> turtle.heading()
Return the distance from the turtle to (x,y), the given vector, or the given
other turtle, in turtle step units.
>>> turtle.home()
>>> turtle.distance(30,40)
>>> turtle.distance((30,40))
>>> joe = Turtle()
>>> joe.forward(77)
>>> turtle.distance(joe)
Set angle measurement units, i.e. set number of “degrees” for a full circle.
Default value is 360 degrees.
>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
>>> # Change angle measurement unit to grad (also known as gon,
>>> # grade, or gradian and equals 1/100-th of the right angle.)
>>> turtle.degrees(400.0)
>>> turtle.heading()
100.0
>>> turtle.degrees(360)
>>> turtle.heading()
turtle.radians()
Set the angle measurement units to radians. Equivalent to
degrees(2*math.pi)
.
>>> turtle.home()
>>> turtle.left(90)
>>> turtle.heading()
>>> turtle.radians()
>>> turtle.heading()
1.5707963267948966
Set the line thickness to width or return it. If resizemode is set to
“auto” and turtleshape is a polygon, that polygon is drawn with the same line
thickness. If no argument is given, the current pensize is returned.
>>> turtle.pensize()
>>> turtle.pensize(10) # from here on lines of width 10 are drawn
Return or set the pen’s attributes in a “pen-dictionary” with the following
key/value pairs:
“shown”: True/False
“pendown”: True/False
“pencolor”: color-string or color-tuple
“fillcolor”: color-string or color-tuple
“pensize”: positive number
“speed”: number in range 0..10
“resizemode”: “auto” or “user” or “noresize”
“stretchfactor”: (positive number, positive number)
“outline”: positive number
“tilt”: number
This dictionary can be used as argument for a subsequent call to pen()
to restore the former pen-state. Moreover one or more of these attributes
can be provided as keyword-arguments. This can be used to set several pen
attributes in one statement.
>>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
>>> sorted(turtle.pen().items())
[('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
('shearfactor', 0.0), ('shown', True), ('speed', 9),
('stretchfactor', (1.0, 1.0)), ('tilt', 0.0)]
>>> penstate=turtle.pen()
>>> turtle.color("yellow", "")
>>> turtle.penup()
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow')]
>>> turtle.pen(penstate, fillcolor="green")
>>> sorted(turtle.pen().items())[:3]
[('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red')]
Four input formats are allowed:
pencolor()
Return the current pencolor as color specification string or
as a tuple (see example). May be used as input to another
color/pencolor/fillcolor call.
pencolor(colorstring)
Set pencolor to colorstring, which is a Tk color specification string,
such as "red"
, "yellow"
, or "#33cc8c"
.
pencolor((r, g, b))
Set pencolor to the RGB color represented by the tuple of r, g, and
b. Each of r, g, and b must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see colormode()
).
pencolor(r, g, b)
Set pencolor to the RGB color represented by r, g, and b. Each of
r, g, and b must be in the range 0..colormode.
If turtleshape is a polygon, the outline of that polygon is drawn with the
newly set pencolor.
>>> colormode()
>>> turtle.pencolor()
'red'
>>> turtle.pencolor("brown")
>>> turtle.pencolor()
'brown'
>>> tup = (0.2, 0.8, 0.55)
>>> turtle.pencolor(tup)
>>> turtle.pencolor()
(0.2, 0.8, 0.5490196078431373)
>>> colormode(255)
>>> turtle.pencolor()
(51.0, 204.0, 140.0)
>>> turtle.pencolor('#32c18f')
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
turtle.fillcolor(*args)
Return or set the fillcolor.
Four input formats are allowed:
fillcolor()
Return the current fillcolor as color specification string, possibly
in tuple format (see example). May be used as input to another
color/pencolor/fillcolor call.
fillcolor(colorstring)
Set fillcolor to colorstring, which is a Tk color specification string,
such as "red"
, "yellow"
, or "#33cc8c"
.
fillcolor((r, g, b))
Set fillcolor to the RGB color represented by the tuple of r, g, and
b. Each of r, g, and b must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see colormode()
).
fillcolor(r, g, b)
Set fillcolor to the RGB color represented by r, g, and b. Each of
r, g, and b must be in the range 0..colormode.
If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.
>>> turtle.fillcolor("violet")
>>> turtle.fillcolor()
'violet'
>>> turtle.pencolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor((50, 193, 143)) # Integers, not floats
>>> turtle.fillcolor()
(50.0, 193.0, 143.0)
>>> turtle.fillcolor('#ffffff')
>>> turtle.fillcolor()
(255.0, 255.0, 255.0)
turtle.color(*args)
Return or set pencolor and fillcolor.
Several input formats are allowed. They use 0 to 3 arguments as
follows:
color()
Return the current pencolor and the current fillcolor as a pair of color
specification strings or tuples as returned by pencolor()
and
fillcolor()
.
color(colorstring)
, color((r,g,b))
, color(r,g,b)
Inputs as in pencolor()
, set both, fillcolor and pencolor, to the
given value.
color(colorstring1, colorstring2)
, color((r1,g1,b1), (r2,g2,b2))
Equivalent to pencolor(colorstring1)
and fillcolor(colorstring2)
and analogously if the other input format is used.
If turtleshape is a polygon, outline and interior of that polygon is drawn
with the newly set colors.
>>> turtle.color("red", "green")
>>> turtle.color()
('red', 'green')
>>> color("#285078", "#a0c8f0")
>>> color()
((40.0, 80.0, 120.0), (160.0, 200.0, 240.0))
turtle.filling()
Return fillstate (True
if filling, False
else).
>>> turtle.begin_fill()
>>> if turtle.filling():
... turtle.pensize(5)
... else:
... turtle.pensize(3)
turtle.end_fill()
Fill the shape drawn after the last call to begin_fill()
.
Whether or not overlap regions for self-intersecting polygons
or multiple shapes are filled depends on the operating system graphics,
type of overlap, and number of overlaps. For example, the Turtle star
above may be either all yellow or have some white regions.
>>> turtle.color("black", "red")
>>> turtle.begin_fill()
>>> turtle.circle(80)
>>> turtle.end_fill()
turtle.reset()
Delete the turtle’s drawings from the screen, re-center the turtle and set
variables to the default values.
>>> turtle.goto(0,-22)
>>> turtle.left(100)
>>> turtle.position()
(0.00,-22.00)
>>> turtle.heading()
100.0
>>> turtle.reset()
>>> turtle.position()
(0.00,0.00)
>>> turtle.heading()
turtle.clear()
Delete the turtle’s drawings from the screen. Do not move turtle. State and
position of the turtle as well as drawings of other turtles are not affected.
turtle.write(arg, move=False, align='left', font=('Arial', 8, 'normal'))
- Parameters:
arg – object to be written to the TurtleScreen
move – True/False
align – one of the strings “left”, “center” or right”
font – a triple (fontname, fontsize, fonttype)
Write text - the string representation of arg - at the current turtle
position according to align (“left”, “center” or “right”) and with the given
font. If move is true, the pen is moved to the bottom-right corner of the
text. By default, move is False
.
>>> turtle.write("Home = ", True, align="center")
>>> turtle.write((0,0), True)
turtle.ht()
Make the turtle invisible. It’s a good idea to do this while you’re in the
middle of doing some complex drawing, because hiding the turtle speeds up the
drawing observably.
>>> turtle.hideturtle()
turtle.isvisible()
Return True
if the Turtle is shown, False
if it’s hidden.
>>> turtle.hideturtle()
>>> turtle.isvisible()
False
>>> turtle.showturtle()
>>> turtle.isvisible()
Set turtle shape to shape with given name or, if name is not given, return
name of current shape. Shape with name must exist in the TurtleScreen’s
shape dictionary. Initially there are the following polygon shapes: “arrow”,
“turtle”, “circle”, “square”, “triangle”, “classic”. To learn about how to
deal with shapes see Screen method register_shape()
.
>>> turtle.shape()
'classic'
>>> turtle.shape("turtle")
>>> turtle.shape()
'turtle'
Set resizemode to one of the values: “auto”, “user”, “noresize”. If rmode
is not given, return current resizemode. Different resizemodes have the
following effects:
“auto”: adapts the appearance of the turtle corresponding to the value of pensize.
“user”: adapts the appearance of the turtle according to the values of
stretchfactor and outlinewidth (outline), which are set by
shapesize()
.
“noresize”: no adaption of the turtle’s appearance takes place.
resizemode("user")
is called by shapesize()
when used with arguments.
>>> turtle.resizemode()
'noresize'
>>> turtle.resizemode("auto")
>>> turtle.resizemode()
'auto'
turtle.shapesize(stretch_wid=None, stretch_len=None, outline=None)
turtle.turtlesize(stretch_wid=None, stretch_len=None, outline=None)
- Parameters:
stretch_wid – positive number
stretch_len – positive number
outline – positive number
Return or set the pen’s attributes x/y-stretchfactors and/or outline. Set
resizemode to “user”. If and only if resizemode is set to “user”, the turtle
will be displayed stretched according to its stretchfactors: stretch_wid is
stretchfactor perpendicular to its orientation, stretch_len is
stretchfactor in direction of its orientation, outline determines the width
of the shape’s outline.
>>> turtle.shapesize()
(1.0, 1.0, 1)
>>> turtle.resizemode("user")
>>> turtle.shapesize(5, 5, 12)
>>> turtle.shapesize()
(5, 5, 12)
>>> turtle.shapesize(outline=8)
>>> turtle.shapesize()
(5, 5, 8)
Set or return the current shearfactor. Shear the turtleshape according to
the given shearfactor shear, which is the tangent of the shear angle.
Do not change the turtle’s heading (direction of movement).
If shear is not given: return the current shearfactor, i. e. the
tangent of the shear angle, by which lines parallel to the
heading of the turtle are sheared.
>>> turtle.shape("circle")
>>> turtle.shapesize(5,2)
>>> turtle.shearfactor(0.5)
>>> turtle.shearfactor()
Rotate the turtleshape by angle from its current tilt-angle, but do not
change the turtle’s heading (direction of movement).