Deborah R. Fowler
Python and Turtle Graphics
Updated on March
29 2013
Updated on April 23 2022
To find the version
you have installed type python, then two minuses and
version (linux, or in Windows cmd window)
python --version
- Class2 (Introduction to
Turtle)
- Class4 (Function, Nested Loops)
- Class6 (Examples of Quilts)
- Class8
(Examples of Input from Files - generated from Houdini)
Documentation is here (select your version) and also https://documentation.help/Python-3.7/turtle.html
The turtle has three main attributes:
- location
- orientation
- a pen(color,width/up/down attributes)
Speeding up the turtle draw
If you do not need to see the animation there are three ways that you can speed up the turtle:
- t.tracer(0) with t.update()
- t.delay(0)
- t.speed(0)
Tracer doesn't update on screen, stops animation, update is used
to update the canvas
Delay determines control of the canvas updates
Speed will speed up the turtle (values 1-10 are increasing, but 0
will draw the sequence of command but not animate the steps)
An example file to test it can be downloaded speedTurtleUp.py
What can you do with turtle?
You can build more complex shapes like
squares, triangles, circles and so on. Combined with control
flow/procedures/recursion we use L-systems to produce fractals.
The module for turtle graphics uses Tkinter
for the underlying graphics.
python -m turtledemo
(If they are not on your home machine you can grab them from this site - download turledemo32.zip)
Example code below (updated for python3.6):
IDLE - On Windows you can use the
Integrated Development Tool (IDE) for Python. This allows help
with formatting in the editor and allows you to run the script.
To type in your script, open a new window under the File menu.
Note: Under Options->Configure IDLE change
the Fonts/Tabs to be larger for in-class display.
Overview of Basic Programming Concepts - Summary with a Turtle
Variables
Some common programming NotationClassic start
>>print("hello world")
hello world
>>print(3)
3
>>someName = 3Lists can also be used. Python is very forgiving about what you are putting into a variable name (C++ is not, and there are reasons which we will discuss in class).
>>print( someName )
3
Truth Statements
Rather than executing sequentially, now we
have selection.
if condition:
# do something
# note that if is a keyword and condition can be any valid
logical condition
For example:
x = 5
if x < 6:
print ( x )
This will only execute the print statement if
the value of x is given a value smaller than six.
Functions
For example:
import turtle
turtle.forward(15)
The above code opens up a graphics window with
a line (and arrow) moved 15 units across the screen.
Note that in python indentation is very
important and it is fussy about tabs and spaces!
Hint: if IDLE indicates an error in indentation check that
your indentation is correct (even if it LOOKS right, if you
copied and pasted it might be wrong).
Now, let's build a drawSquare function (example code is given after the diagrams below with
explanation or by clicking the image):
- Step 1 - draw a
square
- Step 2 - make it more general by adding parameter for size
- Step 3 - set position
- Step 4,5 - loops
- Step 5s - loops continued
- Step 6 - multiple turtles
- Step 7 - shapes
Explanation follows:
import turtle
# This function defines how to draws a turtle square (Step1 code)
def drawSquare():
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
# This calls the function to draw a square
drawSquare()
We can do this all from the command line, but
if we make a mistake or close our session we don't have our
function so let's create this in a file (you can use an editor
like notepad++ or use IDLE (an IDE).
Notice that this draws a square starting at
the origin. It would be nice to be able to put this anywhere in
our window, or be able to make it any size. This is where
parameters come into the picture. So, that set of parentheses ()
is where we give information to the function. Let's say we want
this square to be a certain size.
Let's refine the function (Step 2
code)
import turtle
def drawSquare( size ):
turtle.forward(size)
turtle.right(90)
turtle.forward(size)
turtle.right(90)
turtle.forward(size)
turtle.right(90)
turtle.forward(size)
(Notice that if you run this with idle, the
graphics window will remain open for your convenience. If you
are in geany, you may want to add turtle.exitonclick() at the
end)
Now, suppose we want to start in certain
position, let's add this as well
Note if we put the command to move in, it draws a line - we need
to pick up our pen. You can use penup or up, both do the same
thing, so we add the lines
turtle.up()
turtle.setpos(pos)
turtle.down()
And pos can be
sent in as a parameter (Step 3
code)
Looping
Clearly we can call the function repeatedly.
We can also see that there is repetition in this code. Let's
clean that up with looping. In Python there are for and while
loops. Let's use a for loop to shorten this Step 4 code.
# for
loops iterate in this case from the first value until <
4, so
for i in range
(0,4) :
print i
turtle.forward(size)
turtle.right(90)
Now when we call the function,
we send it the size and pos
Clearly we can add more squares too Step 5 code:
for i in range ( 0 , 40 ) :
drawSquare( 10, ( -400 + i * 20, 0 ) )
This draws a
square of size 10 starting at position -400 + 0 * 20, 0.
Then in the next step of the loop it draws it at -400 + 1 *
20, 0 and then in the next step -400 + 2 * 20, 0 and so on
until it gets to 39 and draws the final square, then it
stops.
Python also has while loops
while condition :
// do something
The above
loop could be written using a while loop as:
(In the sample code here, I have changed the position to be a y value of 20)i = 0
while i < 40 :
drawSquare( 10, -400 + i * 20, 0 ) )
i = i + 1
What if we wanted more turtles?
Just as you can define other variable you can define turtles (Step
6 code)
Extended to two functions, with timing and
message (Step
7 code)
Additional Examples
Finally, take a look at the phyllotaxis demo
example. For
an explanation see the description
of the formula For variety here is TurtleSunflowers.py as well as some sample flowers to get you started in flowers.py.
Exercises
1. Get used to IDLE, python and the turtle by
creating a function to draw a triangle.
2. Practice loops by drawing multiple triangles.
3. Try drawing your initials or your name using
the simple commands you have learned.
If you are working on looping, try printing
"Hello Sunflower" 10 times ... then try printing out Hello Hello
Hello Sunflower Sunflower Sunflower ... do these using a for
loop ... then try getting the same result using a while loop.
Don't forget to go thru the step by step
examples for the drawing of a square. Try it with a triangle.
Recursion
Self similarity occurs often for example in
fractal patterns. Here are two examples of the Koch snowflake
implemented in python.Described at http://commons.wikimedia.org/wiki/Koch_snowflake the python implementation given uses string manipulation ("L-system")
Note that this one is written similar to the definition of the pattern and run for more levels