0% found this document useful (0 votes)
42 views13 pages

Python Turtle Graphics Projects

This document introduces the Python turtle module for drawing graphics. It provides examples of using turtle methods like forward, right, and color to draw basic shapes like squares and stars. Later examples show how to randomize star positions and colors, add grids of circles, and allow the user to save attractive patterns by pressing keys. The goal is to experiment with turtle graphics and practice basic Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views13 pages

Python Turtle Graphics Projects

This document introduces the Python turtle module for drawing graphics. It provides examples of using turtle methods like forward, right, and color to draw basic shapes like squares and stars. Later examples show how to randomize star positions and colors, add grids of circles, and allow the user to save attractive patterns by pressing keys. The goal is to experiment with turtle graphics and practice basic Python programming.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Project 1: Pretty Pictures

So far we have been concerned only with programs which read and write text. But we have been
sitting in front of a computer with graphical elements on the screen as well as textual ones.
There are many ways to produce pictures, both line drawing and photographic, using programming
languages like Python. For this project, we will use the turtle module which uses a model of drawing
invented for children but fun for adults too. In this model, there is a little ‘turtle‘ on screen, and we
direct it where to go, and it leaves a trail behind it as it goes.
To begin, we import the turtle module, and create a new turtle, which we call t:

Python
>>> import turtle
>>> t = [Link]()

Upon typing the second line, a blank window appears, with the turtle represented by an arrow,
pointing to the right:

117
118 Project 1: Pretty Pictures

We can now issue a command for the turtle to follow:

Python
>>> [Link](100)

Here is the result:

We can complete the square by turning repeatedly by ninety degrees and moving forward.

Python
>>> [Link](90)
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)

The final result is a square of side 100, with the turtle in its original position, but pointing upwards:
Project 1: Pretty Pictures 119

We can write a function to make a square of any size:

Python
>>> def square(x):
... for _ in range(4):
... [Link](x)
... [Link](90)

The functions fd and rt are abbreviations for forward and right. The underscore _ is used to indicate
that we are not using the counter from the for loop. We can make a primitive star by using square
multiple times:

Python
>>> for _ in range(10):
... square(100)
... [Link](360/10)

Here is the result:


120 Project 1: Pretty Pictures

When experimenting, the methods home and clear are useful:

Python
>>> [Link]()
>>> [Link]()

The home method moves the turtle to the origin and restores its direction to the default. The clear
function clears the turtle screen.

Q UESTION 1 Write a function many_squares which, given a number of squares to use and a size for
the ‘star‘, draws it.

To make another kind of star, we can use the backward/bk method:

def star(l, n):


for _ in range(n):
[Link](l)
[Link](l)
[Link](360/n)

Here is star(100, 20):


Project 1: Pretty Pictures 121

There is a left/lt equivalent to right/rt as well.

Q UESTION 2 Write a function to draw a polygon with a given number of sides of a given length.
Use this function, together with right turns, to repeat the given polygon multiple times to make a
symmetrical pattern.
Q UESTION 3 Write a function circle, which draws a circle for a given centre position and radius,
choosing the number of sides dependent on size to give a smooth result. If you need π, it can be found
as [Link] after using import math.

So far we have no way to prevent the turtle leaving a trail behind. What if we want to draw multiple
stars? We can use the methods penup (stop drawing a trail) and pendown (resume drawing a trail):

def star(x, y, l, n):


[Link]()
[Link]()
[Link](x)
[Link](90)
[Link](y)
[Link]()
for _ in range(n):
[Link](l)
[Link](l)
[Link](360/n)

Now we can use the random module to draw lots of stars:


122 Project 1: Pretty Pictures

Python
>>>import random
>>>for _ in range(20):
... star([Link](-300, 300),
... [Link](-300, 300),
... [Link](10, 150),
... [Link](3, 30))

Here is the result of one run:

We can simplify by using the method goto which moves to a given coordinate directly. We also use
setheading to start each star at a random angle:

def star(x, y, l, n):


[Link]()
[Link](x, y)
[Link]([Link](0,359))
[Link]()
for _ in range(n):
[Link](l)
[Link](l)
[Link](360/n)
Project 1: Pretty Pictures 123

Q UESTION 4 Using the goto method, write a function to draw a square grid of circles of diameter fifty
which touch one another.

There are two problems with our pictures: they take a long time to draw, and the turtle gets in the
way of the final result. To improve the speed, we use the speed method, which takes a number from 1
(slowest) to 10 (fastest). In addition, the number 0 means that no animation takes place, and the picture
is drawn as quickly as possible. We can stop the turtle getting in the way of our final picture by using
the hideturtle method (it has an opposite in showturtle). Try this:

Python
>>> [Link]()
>>> [Link](0)
>>> star(0, 0, 200, 7)
>>> [Link]()

The method pensize can be used to change the thickness of the trail. The pencolor method may be
used to change the colour. The default pen width is 1 and, as we know, the default pen colour is black,
which is the same as the red-green-blue triple (0, 0, 0). Consider this sequence of commands, where we
use various shades of grey from black (0, 0, 0) to white (1, 1, 1):

Python
>>> [Link](20)
>>> star(0, 0, 200, 7)
>>> [Link](15)
>>> [Link](0.25, 0.25, 0.25)
>>> star(0, 0, 200, 7)
>>> [Link](10)
>>> [Link](0.5, 0.5, 0.5)
>>> star(0, 0, 200, 7)
>>> [Link](5)
>>> [Link](0.75, 0.75, 0.75)
>>> star(0, 0, 200, 7)
>>> [Link](2)
>>> [Link](1, 1, 1)
>>> star(0, 0, 200, 7)
>>> [Link]()

Here is the result:


124 Project 1: Pretty Pictures

Q UESTION 5 Write a program to display the whole gamut of colours available in the RGB space. That
is to say, all combinations of red, green and blue, with a reasonable granularity – perhaps steps of 0.1.

The turtle module provides its own functions for drawing filled shapes:

Python
>>> t.begin_fill()
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)
>>> [Link](90)
>>> [Link](100)
>>> t.end_fill()
>>> [Link]()
Project 1: Pretty Pictures 125

The fill colour can be set with fillcolor. To make a filled shape with no border, make sure the pen is
up.

Q UESTION 6 Modify your circle program to draw a filled circle.

Some of our arrangements of stars were prettier than others. Let us write a program to allow the user
to see one after another, and when a nice one appears, to save it to file. Each image will be drawn in
turn, requiring the Space key to be pressed to go to the next one. Pressing ’s’ instead will save the file.
Pressing ’x’ will quit the program. We shall be using our usual star function.
To begin with, we shall define three functions, to make the display, to leave the program, and to
save the picture, to be triggered by the Space key, ‘x’ key, and ‘s’ key respectively:

import sys

def many_stars():
[Link]()
for _ in range(20):
star([Link](-300, 300),
[Link](-300, 300),
[Link](10, 150),
[Link](3, 30))

def stars_exit():
[Link](0)

def save_stars():
[Link]().getcanvas().postscript(file='[Link]')
stars_exit()
126 Project 1: Pretty Pictures

The function exit from the sys module exits the current program (the 0 indicates an ordinary exit, as
opposed to one caused by an error). It is preferable to the plain exit() we have been using thus far,
which is intended only for use in interactive Python. The long line in save_stars is an incantation
(which you need not understand) to save the contents of the turtle screen to the file [Link]. This
a so-called PostScript file, which you may open on your computer to show it. PostScript is quite an
old-fashioned format, so you might need to download a program to view it.
Now, we set up the screen, hiding the turtle, setting the speed to maximum and turning animation
off. We then tell the turtle module we wish to link certain keys to certain of our functions: they will
be run each time the given key is pressed.

[Link]()
[Link]().tracer(0, 0)
[Link]().onkey(save_stars, 's')
[Link]().onkey(many_stars, ' ')
[Link]().onkey(stars_exit, 'x')

Finally, we ask the turtle module to listen to the window for these keys, run our many_stars function
once to draw the first pattern, and call [Link]() to begin listening for the keys.

[Link]()
many_stars()
[Link]()

The [Link]() line must be the last statement in the program. Here is the whole program:

import turtle
import random
import sys

def star(x, y, l, n):


[Link]()
[Link](x, y)
[Link]([Link](0, 359))
[Link]()
for _ in range(n):
[Link](l)
[Link](l)
[Link](360.0 / n)

def many_stars():
[Link]()
for _ in range(20):
star([Link](-300, 300),
[Link](-300, 300),
[Link](10, 150),
[Link](3, 30))

def stars_exit():
Project 1: Pretty Pictures 127

[Link](0)

def save_stars():
[Link]().getcanvas().postscript(file='[Link]')
stars_exit()

t = [Link]()

[Link]()
[Link]().tracer(0, 0)
[Link]().onkey(save_stars, 's')
[Link]().onkey(many_stars, ' ')
[Link]().onkey(stars_exit, 'x')
[Link]()

manystars()
[Link]()

As well as key presses, we can detect mouse clicks, by using the function Screen().onscreenclick
providing a function of which takes the x and y coordinates of the click. Here is a program to draw a
star at any location clicked by the user:

import turtle
import random

def star(x, y, l, n):


[Link]()
[Link](x, y)
[Link]([Link](0, 359))
[Link]()
for _ in range(n):
[Link](l)
[Link](l)
[Link](360.0 / n)

def draw_star(x, y):


star(x, y, [Link](10, 150), [Link](3, 30))
[Link]().update()

t = [Link]()
[Link]().tracer(0, 0)
[Link]()
[Link]()
[Link]().onscreenclick(draw_star)
[Link]()

Now let us use what we have learned to write two more substantial programs.
128 Project 1: Pretty Pictures

P ROJECT 1A: A G RAPH P LOTTER


Write a program which takes one or more formulae on the command line and plots them. For example,
we might see:

For the text on the axes, and for the labels, you will need to use the turtle function write. For example,
the following will write the text ‘Hello‘ at the current position in 16pt Arial:

Python
>>>[Link]('Hello', font = ('Arial', 16, 'normal'))

Remember that the built-in Python function eval can evaluate a given piece of Python program. For
example, if the variable x has value 10 the result of eval('x * 2') is 20.
The answer to this first part can be found at the back of the book; answers to the following
extensions are not given.

E XTENSIONS:

• Allow the axes to be set on the command line, including scaling in x and y directions.
• Use [Link]().input to ask for the formulae, if none are given on the command line –
the program is then interactive.
• Allow for the plotting of graphs using polar coordinates, graphs parameterised in terms of x
and y, and so on.
Project 1: Pretty Pictures 129

P ROJECT 1B: A C LOCK Write a clock program, which displays the current time on an analog clock,
updating once a second. For example:

You will need the time module for this. If we have a function clockface, we can pass it the current
time like this:

import time

tm = [Link]()

clockface(tm.tm_hour, tm.tm_min, tm.tm_sec)

The answer to this first part can be found at the back of the book; answers to the following extensions
are not given.
E XTENSIONS:
• Add the hour labels 1..12 to the clock.
• Make a prettier clock face and prettier hands, perhaps based on a clock in your house.
• Add a digital clock and an alarm function.

Common questions

Powered by AI

Importing the random module allows for introducing variability in drawings, such as randomizing positions, angles, and shape sizes, enhancing creativity and diversity in outputs. Importing math provides access to functions like math.pi, essential for calculations involving circles and precise mathematical computations, thereby enhancing the precision and functionality of graphical programming with turtle .

The turtle module is an effective educational tool due to its visual feedback, making abstract programming concepts tangible. It facilitates learning loops, functions, and conditionals by directly visualizing them as geometric patterns on the screen, providing immediate, intuitive understanding. This can engage learners and clarify abstract concepts through trial and error and creative experimentation. However, limitations include its slower processing and basic graphics compared to more advanced graphical tools .

The goto method moves the turtle directly to specified (x, y) coordinates without following the screen path it would normally draw, which helps in positioning the turtle directly. This is advantageous in complex patterns where precise positioning is required between drawings without leaving trails or requiring complex calculation of angles and distances .

The penup and pendown methods control whether the turtle leaves a trail while moving. Use penup() before moving to a new starting point without drawing, and pendown() to resume drawing a shape. This is especially useful when drawing multiple shapes separately, as it allows for precise control of when drawing begins, avoiding unintended lines connecting different shapes .

While creating filled shapes in turtle graphics, a visible border can remain unless addressed by first using t.penup() to lift the pen during filling. To prevent the border, begin by setting the fill color, proceeding with t.begin_fill(), drawing the shape borders, and finally using t.end_fill(). Setting the pen color the same as the fill color if borders are unavoidable also reduces visible borders .

The onkey method links keyboard keys to specific functions, allowing predefined actions when those keys are pressed. You can define handlers for keys, such as 's' to save, space to generate new designs, and 'x' to exit. This enables interactive applications where the user can control the drawing process through keyboard inputs, providing an engaging and responsive user experience .

To draw a geometric shape filled with color using the turtle module, you must begin by setting the fill color with t.fillcolor(r, g, b) where r, g, and b are the color values. Before starting the drawing, use t.begin_fill() and then execute the drawing commands (such as t.fd(100) and t.rt(90) for a square). To complete, use t.end_fill() to close the shape and fill it with the chosen color .

To increase visual complexity, the turtle module can utilize randomness for varying positions, angles, and sizes of shapes, as demonstrated in programs using random.randint for coordinates and sizes. Additional complexity is achieved using different shapes, filled shapes, varying colors with pensize and pencolor methods, and layering drawings through coordinated penup/pendown actions .

Using the turtle speed method optimizes rendering by adjusting the speed at which shapes are drawn. The speed can be set from 1 (slow) to 10 (fast), with 0 for no animation. This allows fast drawing of complex pictures without user-experienced delays. However, the challenge lies in balancing speed with visibility of drawing processes, as faster speeds may hinder understanding of the drawing steps .

Effective integration of user input in turtle graphics can be achieved by using input functions such as Screen().onscreenclick for mouse interactions and onkey for keyboard inputs. These allow responsive drawing actions based on user interaction. For example, clicking to position and create stars or using keyboard shortcuts to iterate through designs or save creations fosters interactivity, enhancing user engagement with real-time feedback and adaptability .

You might also like