Turtle Graphics

We can create graphics in Python by using a turtle. This is an imaginary pointer that we can instruct to move around the screen.

The Spiral (spiral.py)

Our first turtle program is going to create a spiral by drawing lines of every greater length before turning through 90 degrees.

Open up a new python file and type in the following code:

Circle Spiral

We can also draw basic shapes with turtle. Let's try the circle command.

Color

We can add colour to our turtle by using the pencolor command. Modify your code to set the pen to red

One colour is a bit boring though. We can store several colours in a list and get python to cycle through them.

  • In almost all programming languages, list entries are numbered starting from 0. So colors[0] = red, colors[1] = yellow etc.

  • x % 4 (said as x mod 4) calculates the remainder when x is divided by 4. So in our loop this will cycle through 0,1,2,3

Changing Background Colours

Of course, your images will look much better if the background was darker. We can set the background colour using the bgcolor command:

turtle.bgcolor("black")

Adding Complexity

We're now going to add some complexity to our programmes to make our images look even better. Take a look at the following code:

Lets look at the changes one at a time:

  • sides = 6 : In the examples above we had squares, i.e 4 sides. Now we want to store the number of sides in a variable so that we can change it easily.

  • for x in range (360) : Not much of a change here but we're going to create a bigger picture by going to 360

  • colors = ["red", "yellow", "blue", "orange", "green", "purple"] : More colours. Well why not!

  • t.forward(x * 3 / sides + x) : This adds some complexity to our image, moving the turtle forward more with each loop. Can you work out what it's doing?

  • t.left(360/sides + 1) : Before we were turning left 90 + 1 degrees because we had a square. 360/4 = 90. Now we want to create a shape with however many sides we have stored in our variable.

  • t.width(x*sides/100) : Again, this is adding more complexity. The width command sets how wide our pen mark will be, gradually increasing the width as the spiral moves out.

On a Mac, you can take a screenshot by pressing Command-shift-4 and selecting the area that you want to screenshot. A file of the screenshot will be saved on your desktop.

Extension

We can even ask the user how many sides they would like. Replace the line side=6 with the following:

sides = eval( input("Enter a number of sides between 2 and 6: ") )

This takes an input from the user and uses the eval() function to convert it in to a number that the computer can use.

Last updated

Was this helpful?