Let's dive in and draw squares with the turtle graphics module and a sequence of turtle movement commands.
In the Geany editor and create a new file called 'turtle-square.py'
, and enter the following code:
from turtle import *
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
forward(100)
right(90)
exitonclick()
Save your typing and run the program using the Geany 'Build->Execute'
menu option, or F5
key. You should see a new window appear and a square being drawn.
So, what's actually going on here?
First there's the import statement. As we saw earlier with TKinter GUI module using this style of import means we don't need to use a 'turtle.'
prefix for every function call.
Now for our turtle move commands. Imagine you are drawing a square on a piece of paper using a pencil and a ruler. We can imitate the motion of the pencil with a series of directional and turn commands sent to our turtle.
The first command is the 'forward(100)'
function call. This will move 100 steps in the direction the turtle is already pointing, drawing a line as it goes. Next we need to turn the turtle. The command 'right(90)'
turns the turtle by a specified angle, in this case it's 90 degrees.
Now we simply repeat the 'forward'
and 'right'
commands another three times, to finish drawing our square.
The last line just ensures we can see what the turtle has drawn before the window closes. The program waits until we click somewhere inside the window - or the window's close button is clicked.
And there you have it, your first turtle graphics program.
A post from my Learn Python on the Raspberry Pi tutorial.