Turtle
Python's turtle is the drawing module most first exercises are written in: a turtle carries a pen, and draws a line as it walks. It works in Circuitry. A turtle program from a book, a worksheet or a website runs as it is written, and draws in the preview beside the code.
import turtle
t = turtle.Turtle()
t.shape("turtle")
t.color("green")
t.pensize(3)
for side in range(4):
t.forward(150)
t.left(90)
turtle.done()
Make a Python file, paste that in, and press Run. The preview opens and the turtle draws a square, one side at a time.
There is nothing to install, and it is the same on an iPhone, an iPad, a computer and in a web browser.
Both ways of writing it
Some exercises make a turtle and tell it what to do, as above. Others bring in every turtle function and call them directly. Both work:
from turtle import *
color("red")
forward(100)
left(90)
forward(100)
done()
The second way uses one turtle that is made for you the first time it is needed.
The window
- The preview is the turtle's window. It starts white, like Python's own.
(0, 0)is the middle. x goes right and y goes up, sogoto(100, 50)is right and up from the middle.- Angles are in degrees.
left(90)is a quarter turn.radians()switches to radians anddegrees()switches back. - The window is at least 600 wide and 500 high. If the preview is smaller than that (on a phone, or beside the code), the whole window is shown smaller, so a drawing made for a computer screen still fits.
screen.setup(800, 600)asks for a window of that size. It is shown smaller if the preview is smaller.
How fast it draws
The turtle moves as you watch, which is the point of it. To change that:
| Call | What it does |
|---|---|
t.speed(1) to t.speed(10) | Slow to fast. A new turtle is at 3. |
t.speed(0) | No movement: each line appears at once. |
screen.tracer(0) | Nothing is shown until screen.update(). For a big drawing, or a game. |
screen.update() | Show everything drawn since the last update. |
A drawing made with tracer(0) and never updated is shown when the program ends.
Filling a shape
Everything drawn between begin_fill() and end_fill() is the edge of a shape, and end_fill() colours it in. color("orange", "gold") sets the line and the filling.
import turtle
t = turtle.Turtle()
t.color("orange", "gold")
t.pensize(3)
t.penup()
t.goto(-120, 40)
t.pendown()
t.begin_fill()
for point in range(5):
t.forward(240)
t.right(144)
t.end_fill()
t.hideturtle()
turtle.done()
Where a shape crosses itself, the part in the middle is left empty, as it is in Python's turtle on Windows.
A colour is a name ("red", "light blue", "midnight blue"), a code ("#ff8800"), or three numbers from 0 to 1 ((1, 0.5, 0)). After screen.colormode(255) the three numbers go from 0 to 255.
A loop of colours
import turtle
colours = ["red", "orange", "yellow", "green", "blue", "purple"]
screen = turtle.Screen()
screen.bgcolor("black")
t = turtle.Turtle()
t.speed(10)
t.pensize(2)
for step in range(150):
t.pencolor(colours[step % 6])
t.forward(step * 1.5)
t.left(59)
t.hideturtle()
turtle.done()
Keys, clicks and timers
A program can call your own functions when a key is pressed, when the preview is clicked or tapped, or after a wait.
import turtle
screen = turtle.Screen()
screen.bgcolor("midnight blue")
t = turtle.Turtle()
t.shape("turtle")
t.color("white", "lime green")
t.pensize(3)
t.speed(0)
label = turtle.Turtle()
label.hideturtle()
label.penup()
label.color("white")
label.goto(0, 200)
label.write("Arrow keys move. Space clears. Click to jump.", align="center", font=("Arial", 14, "normal"))
def up():
t.setheading(90)
t.forward(20)
def down():
t.setheading(270)
t.forward(20)
def left():
t.setheading(180)
t.forward(20)
def right():
t.setheading(0)
t.forward(20)
def clean():
t.clear()
def jump(x, y):
t.penup()
t.goto(x, y)
t.pendown()
screen.listen()
screen.onkeypress(up, "Up")
screen.onkeypress(down, "Down")
screen.onkeypress(left, "Left")
screen.onkeypress(right, "Right")
screen.onkey(clean, "space")
screen.onclick(jump)
screen.mainloop()
Click the preview once first, so that the keys go to it and not to the code.
| Call | When your function is called |
|---|---|
screen.onkeypress(go, "Up") | When the key goes down, and again while it is held. |
screen.onkey(go, "Up") | When the key is let go. |
screen.onclick(go) | When the preview is clicked or tapped. Your function gets x and y. |
t.onclick(go) | When that turtle is clicked. t.ondrag(t.goto) lets it be dragged. |
screen.ontimer(go, 500) | Once, 500 thousandths of a second from now. |
Key names are Python's: "Up", "Down", "Left", "Right", "space", "Return", "Escape", or a letter like "a".
Give the function's name with no brackets: screen.onkey(go, "Up"), not screen.onkey(go(), "Up").
A phone or a tablet with no keyboard has no keys to press. Use screen.onclick there.
Games
The usual shape of a turtle game works: turn the drawing off, then go round a loop for ever, moving things and calling update().
import turtle
import time
screen = turtle.Screen()
screen.bgcolor("black")
screen.tracer(0)
ball = turtle.Turtle()
ball.shape("circle")
ball.color("white")
ball.penup()
dx = 4
while True:
screen.update()
ball.setx(ball.xcor() + dx)
if ball.xcor() > 280 or ball.xcor() < -280:
dx = -dx
time.sleep(0.02)
Press Stop to end it.
time.sleepsets the pace, as it does on a computer.- A loop with no sleep goes round 200 times a second on every device. (Python's own turtle goes as fast as the computer lets it, which is why such games run at different speeds on different computers.)
- The loop can be at the top level of the file, or inside a function you defined at the top level and call by its name, such as
def main():thenmain().
One place a loop that never ends does not work: inside a method of a class, or in a function that is handed to something else rather than called by name. The program stops with a message that says so. Move the loop to the top level, or have each step ask for the next one:
def step():
ball.forward(2)
screen.update()
screen.ontimer(step, 20)
step()
screen.mainloop()
Ending
turtle.done(), screen.mainloop() and screen.exitonclick() are the usual last line. Here the picture stays in the preview whether you write one or not. With keys, clicks or timers set, the program keeps running until you press Stop; screen.bye() ends it from the program.
What is different here
- The window does not open on its own: it is the preview.
title()is accepted and shows nowhere. - A turtle that is hidden with its pen up moves at once, since there is nothing to watch.
write(..., move=True)moves the turtle by about the width of the words, not exactly.- If the preview is resized after a program has ended, the picture stays as it was until you press Run again.
- A turtle program's own functions called
draw,updateorsetupare just its own. (In a Pyctures scene those names are called for you.) - A turtle file cannot be made into a web page with File, Export as Web Page.
What is not available yet
Each of these stops the program with a message that names it:
undo()- Picture shapes and backgrounds:
register_shape("ship.gif"),bgpic(). Shapes of your own made from points work:screen.register_shape("kite", ((0, 0), (10, -5), (0, 10), (-10, -5))). textinput()andnuminput()getcanvas(), and anything else that reaches into Tk, the window toolkit Python's turtle is built on. A turtle inside a tkinter window of your own is not run in the preview.
If a name is mistyped, the message gives the nearest one: t.fowrard(10) says Did you mean forward?
Every function
Moving: forward fd backward bk back left lt right rt goto setpos setposition teleport setx sety setheading seth home circle dot stamp clearstamp clearstamps speed
Asking: position pos xcor ycor heading towards distance isdown isvisible filling
The pen: pendown pd down penup pu up pensize width pen pencolor fillcolor color begin_fill end_fill write clear reset
How the turtle looks: showturtle st hideturtle ht shape shapesize turtlesize tilt tiltangle clone. The shapes are "classic", "arrow", "turtle", "circle", "square", "triangle" and "blank".
The screen: Screen bgcolor title setup screensize setworldcoordinates window_width window_height tracer update delay colormode mode turtles getshapes register_shape addshape clearscreen resetscreen
Keys, clicks and timers: listen onkey onkeypress onkeyrelease onclick onscreenclick onrelease ondrag ontimer
Ending: done mainloop exitonclick bye
Angles: degrees radians
Turtle or Pyctures?
Turtle is the way in that most courses use, and everything you learn with it is ordinary Python. When you want pictures, sprites, sound, 3D or a faster game, Pyctures draws in the same preview with a few plain functions: circle, rect, text and a draw() that is called every frame.