Python Resources

Updated on Aug 4 2024

Python and Turtle Graphics

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

Note: This page was originally created specifically for VSFX 705 Spring 2013. It has been modified for VSFX 160 (starting Fall 2018) and 705 (starting Winter 2022). If you are not familiar with turtle graphics, a series of lectures notes are now on my Intro to Programming page. Related directly to turtle and additional example files see
Turtle Graphics will be used in class to demonstrate basic python code. Specifically, we will be using python.

Documentation is here (select your version) and also https://documentation.help/Python-3.7/turtle.html

The turtle has three main 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:

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.

There is a table of the good examples listed in the documentation in section 24.1.7 turtledemo - some of these go into object oriented programming which we will tackle later in the quarter. Type:

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 Notation

Classic start
>>print("hello world")
hello world
>>print(3)
3

or you could store the values in variable
>>someName = 3
 >>print( someName )
 3

Lists 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).


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):


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:

i = 0
while i  <  40 :
    drawSquare( 10, -400 + i * 20,  0 ) )
    i = i + 1

(In the sample code here, I have changed the position to be a y value of 20)

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. MISSING IMAGEFor 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.
MISSING IMAGEDescribed at http://commons.wikimedia.org/wiki/Koch_snowflake the python implementation given uses string manipulation ("L-system")

MISSING IMAGENote that this one is written similar to the definition of the pattern and run for more levels