Functions: There’s a Name for That 165
In this new version, we change the function’s definition to
reflect the new name and the two parameters that we will receive to
draw at chosen positions on the screen as spiral(x,y). We still choose
a random color and size for each spiral, but we have removed the
two lines that generate a random x and y, because we will get the x
and y as arguments from the onscreenclick() listener. Just as with
the random_spiral() function, we move the pen to the correct (x, y)
position and then draw the spiral.
The only step left is to set up our turtle window and the list
of colors, and then tell our turtle.onscreenclick() listener to call the
spiral function whenever the user clicks the mouse button over the
drawing window. Here’s the complete program:
ClickSpiral.py
import random
import turtle
t = turtle.Pen()
t.speed(0)
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green", "orange", "purple",
"white", "gray"]
def spiral(x,y):
t.pencolor(random.choice(colors))
size = random.randint(10,40)
t.penup()
t.setpos(x,y)
t.pendown()
for m in range(size):
t.forward(m*2)
t.left(91)
u turtle.onscreenclick(spiral)
As in TurtleDraw.py, we leave out the parentheses and param-
eters for our callback function u: turtle.onscreenclick(spiral) tells
our program that it should call our spiral(x,y) function every time
the user clicks the mouse on the screen, and the event listener
automatically sends two arguments—the x-position and y-position
of that click—to the spiral callback function. The same thing hap-
pened in TurtleDraw.py with the t.setpos callback, but this time,
we created our own function to draw a spiral of a random color and
size at the location of the mouse button click.