the docs said:
Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.
Python docs - Turtle Graphics
This link is for Python 3.3, there is a drop-down list at the top-left if you are using a different version of Python.
- Poking His Head Out
- Some Settings
- Moving Without Drawing
- Square Pants
- For Loops (and Range)
- Stamping: Our Turtle Makes an Impression!
- Tracey Triangle (Equilateral)
- Filling In
- The Right Angle
- Finish with a Function
Part Two is here
Poking His Head Out
You can explore turtle graphics interactively using the IDLE editor, as shown in the following screenshot.
turtle uses the tkinter module which is installed with most versions of Python, so it should only require the following as the first line in your code:
The turtle can be controlled just by typing turtle.somemethod(). This is using the default instance of the turtle. I'm sure that you would rather name your turtle, so use:
import turtle timmy = turtle.Turtle() timmy.forward(100) # pixels timmy.left(90) # degrees timmy.forward(120)
This works fine in IDLE but in a fuller Editor or IDE (Integrated Development Environment) a few more lines should be added:
import turtle scr = turtle.Screen() # our turtle's playground timmy = turtle.Turtle() timmy.forward(100) timmy.left(90) timmy.forward(120) scr.mainloop() # wait for the turtle-window to be closed
Screen() and Turtle() are constructors that allow us to manipulate the turtle's window (playground) and to create a new turtle. mainloop() is necessary to keep the screen open until we are ready - close the window using the cross at the top-right (in Windows). Do not use mainloop() with the IDLE editor.
We can create, and control, a number of different turtles if we want to:
tracey = turtle.Turtle()
When naming your turtle just use letters of the alphabet, although you can include a number (as long as it is not the first character). You could also use underscores but, again, don't use this as the first character:
square_pants = turtle.Turtle()
The turtle starts in the centre of the screen, at position (0, 0), and facing East. timmy.forward(100) moves timmy forward, in the direction he is currently facing, a distance of 100 pixels. Notice that he draws a line as he moves.
timmy.left(90) turns timmy left by 90 degrees; again, it is important to understand that this is "90 degress left from the direction he is currently facing".
Timmy can also move .backward(50) and turn right(90). This is the same as going forward(-50) and left(270) but I am sure you will find it less confusing to stick to forward/backward and left/right.
There are many abbreviations that you can use such as fd(), bk(), back() for forward() and backward(). I prefer to use the full words and I think this makes the code easier to read (and more obvious!).
There are a number of settings that we can change, best illustrated with an example:
Explore Spend some time exploring this code. Get timmy to move in different directions, try different pen-sizes, etc.. Explore the colours. There are many colour-names that you can use: orange, purple, pink, lightblue, etc.. If you want to use an image for the background make sure that it is a .gif file, a reasonable size, and is saved in the same location as the python file.
Moving Without Drawing
Use timmy.penup() to prevent our turtle from drawing a line as he moves. Use timmy.pendown() to start drawing the line again.
As the following code shows, we can also use goto(x, y) to move to a specific location. x and y can be positive or negative values. Use negative numbers to move to the left and/or down. The values are measured from the turtle's home at (0, 0). Note, however, that a line will still be drawn when using goto() unless you first use penup(). You can prove this just by commenting out the penup() statement on line 20. To comment out a line (so that it is ignored) type a hash-sign # at the beginning of the line.
Note: As well as goto() there is also home() which returns our turtle to his starting-position (0, 0).
We can also use setx(value) and sety(value) to change the x or y position, leaving y or x (respectively) unchanged. That is, just moving the turtle vertically or horizontally.
A square has four sides of equal length and each internal angle is 90 degrees. When drawing a square on graph-paper it is quite common to mark the four corners and then draw straight-lines between them. Often we might want to position the square from a certain location, so we might first work out where the bottom-left corner is; that is, how far away it is from the origin (0, 0).
Drawing with the turtle is a little different. It might help to imagine yourself sitting on-top of the turtle and facing in the same direction. (Of course, it would need to be a Giant Turtle!) To draw a square he moves forward a distance, turns left 90 degrees, moves forward the same distance as before, then turns left again. If he repeats this sequence four times he will end up where he started, but leaving a nice square in his wake.
He doesn't have to turn left - he could turn right, but he would need to turn right four times to complete the square.
Thinking about it in this way might take a little getting used to. (It helps to slow the turtle down using speed()). However, there are a number of advantages. Most significantly, the turtle doesn't care where he is positioned, or what direction he is facing: as long as he completes the four steps we will always end up with a square. We can draw a square anywhere on his Screen, and tilted at any angle, just by repeating the four movements!
Explore Try different colours, shapes, and using goto() and left() (or right()) to draw different squares, starting at different positions and angles. Don't forget to use penup() and pendown() if you want to move the turtle without drawing a line.
You should notice that we are repeating the same instructions (called statements) over and over. For more complex shapes and diagrams we might end up with lots of the same statements being repeated. This means a lot of typing, or copying, and it is more likely for us to make mistakes. What we need is a way to repeat the same statements, without re-typing them. Hello to Loops!
For Loops (and Range)
for x in [1, 2, 3, 4]: # statements that will be repeated 4 times pass
- for and in are Python keywords - part of the language of Python.
- x is the name of a variable. You can use any (reasonable) name, but you'll often see code using either x or i when, effectively, counting. It is sometimes called a counter variable or sentinel.
- [1, 2, 3, 4] is a List containing the four numbers.
- The for-statement needs to have a colon : at the end of the statement.
- The lines (statements) that follow this line will be repeated a certain number of times.
- These statements must be indented so that Python understands that they form the body of the loop (that is, the statements that need to be repeated).
- You can either Tab in, or use spaces, to create the indent, but the indent must be the same for all the lines that need to be repeated. (That is, unless these statements include another block-structure; but you don't need to be concerned about this for a while.)
- Each time the statements are repeated x will assume the values of 1, then 2, etc. Hopefully you can see that this will repeat the statements four times in total.
A variable is a location in the computer's memory that we can use to temporarily store a value of some kind: a number, a piece of text, a date, etc.. To help us work with the value we give the variable a name (x, table, user_name, eric). We can then use this name to refer to, and change, its value in our code.
Rather than creating a List using [..] we can use the range(start, stop, step) function to create a sequence of numbers. Change the for-line to the following and run the code again.
for x in range(4):
This actually gives x the values 0, 1, 2, 3 within the loop. This doesn't matter though, as we are not using the values of x within the loop. As long as there are four-values it will cause code to be repeated four times. If you really wanted to use the numbers 1, 2, 3, 4 then you could write:
for x in range(1, 5):
This looks odd to me, as it just seems intuitive that it should end at the value 5, not 4. I encourage you to get used to counting starting at 0 (using range(4)). All modern programming languages do this, even VB.NET!
To repeat statements four times we just need something (an iterable) that contains four items/elements. We can take advantage of this fact by creating, and looping through, a List of four colours. We can assign our list of four colours to a variable:
colours = ["red", "green", "blue", "cyan"]
Stamping: Our Turtle Makes an Impression!
At any point we can use stamp() to leave an imprint of the current turtle (its shape and colour) at its current position. You can modify the previous code to the following version:
penup() means that it will not draw lines between the stamps. (This also confirms that the pen doesn't need to be down in order to leave an impression.)
Tracey Triangle (Equilateral)
An equilateral triangle has sides of the same length. This is similar to drawing a square: we need three loops (iterations) and the internal angle between each line is 60 degrees.
The internal angles of a triangle add up to 180 degrees. For an equilateral triangle these angles are equally split at 60 degrees each.
However, when the turtle is facing forward, she needs to turn 120 degrees so that the angle between the line she has just drawn, and the line she is about to draw, is 60 degrees. (The line she is on represents an angle of 180 degrees.)
A slight difference for this example is that we first move tracey to a different location, and change the angle she is facing. Notice that this has no effect on her ability to draw a triangle.
Filling a shape or area with colour is achieved by:
- Using turtle.fillcolor("red") to choose a colour.
- turtle.begin_fill() to confirm that you will be filling an area.
- After moving the turtle around use turtle.end_fill() to fill the area.
If you have completed the outline of an area then it is this area that will be filled. If you stop before you've completed the shape then the turtle will fill the area that would be completed if the turtle returned to the location it was at when begin_fill() was used. To see this effect change the number 3 to 2 in the code that follows.
This can be very useful because the turtle doesn't have to complete a full area and can be left at a different location than he started from. It can also catch us out, though, if the turtle doesn't end-up at a suitable location. (You might end-up with an oddly-shaped block of colour?!) Practice and experience will enable you to take advantage of this behaviour.
In this example I've also turned off the pen (penup()) so that a border won't be drawn around the shape. An alternative would be to make the pencolor() the same as the fillcolor().
The Right Angle
If we complete the adjacent and opposite sides of a right-angled triangle we can use pythagoras' theorem to determine the length of the remaining side (the hypotenuse). However, we still need to work out what angle our turtle needs to turn in order to correctly close the triangle.
While I'm happy to teach turtle graphics and Python, this isn't the place for me to attempt to teach mathematics (geometry). You can study the following code, which also demonstrates using the math module.
I am going to cheat though. I mean, take advantage of the turtle's behaviour and methods. In order for timmy to draw the first two lines, he must start from a certain point and move forward from there. If we can store his starting-point we can just use goto() to return him to this point - closing the triangle in the process. position() gives us the turtle's current position which we can store in a variable.
When creating this example I realised that it no longer needs to be a right-angled triangle. In fact, if we store the starting-position, we can use this to complete any shape that we are drawing. I mention this only as a small example of the little gems, and pieces of inspiration, that you will encounter on your programming journey! I started by investigating (revising) some arithmetic and geometry so that I could complete a right-angled triangle, and ended-up with a simple approach that I could use to complete any shape whatsoever.
Finish with a Function
A Python function is a block of re-usable code. When we want to use the function we call it, passing it any information it requires - arguments for the function. Functions can also return a value (to the code that called the function), but we won't look into that here.
We declare a function using a def statement:
def function_name(parameters): # function code # this code needs to be indented at the same level pass
- The keyword def stands for function definition.
- Give the function a meaningful name.
- Within the (required) brackets you can list parameters - values that will be passed to the function.
- The def-statement is completed by the colon : (required).
- Indent the code of the function at the same level.
See the notes that follow this example, which draws a square for our turtle:
import turtle scr = turtle.Screen() timmy = turtle.Turtle() def square(aturtle, side): for x in range(4): aturtle.forward(side) aturtle.left(90) square(timmy, 120) scr.mainloop()
The name of our function is square. It accepts two arguments, which are our turtle and the length of the sides for our square. We can use (call) this function at any time, passing it our turtle, or any other turtle that we have, and the length of the square's sides that we want to draw. square(timmy, 120) calls the function.
When we define (using def) our function, the variables in the brackets are the function's parameters. When the function is called we pass the function specific values, called arguments. However, you will frequently encounter the words parameter and argument used interchangeably.
I'll stop here, but repeat the link for the official Python documentation for the turtle graphics:
Python docs - Turtle Graphics
I hope this tutorial has given you a good start with turtle graphics (and Python)! Enjoy, it is quite interesting working with the turtle, and it is a good way of getting into programming.
Added: Part Two is here
This post has been edited by andrewsw: 04 October 2013 - 01:09 PM