166 Chapter 7
t king a it one step Further:
clickandsmile
Let’s extend this interactive app by making one more change.
Instead of drawing a spiral, say we want to draw a smiley face
wherever the user clicks the mouse on the drawing screen.
The code will look a lot like our RandomSmileys.py program
from page 151, but instead of a loop that draws 50 smiley faces
at random locations on the screen, this program will handle the
mouse click event by drawing a smiley at the location the user
chooses, as many or as few times as the user wishes to click.
In fact, because our draw_smiley() function already takes two
parameters (the x- and y-coordinates of the location where we
wish to draw the smiley face), the code for ClickAndSmile.py is
identical to RandomSmileys.py, except for the last section. Just
replace the for loop that draws 50 random smileys with a call
to turtle.onscreenclick(draw_smiley). Remember how the turtle
.onscreenclick() function allows us to pass the name of a function
(like setpos) as the event handler for mouse clicks? We can pass
it draw_smiley so that when the user clicks, our draw_smiley() func-
tion will do its work at the location of the click. We do not include
draw_smiley’s parentheses, or any arguments, inside the parentheses
for turtle.onscreenclick().
ClickAndSmile.py
import random
import turtle
t = turtle.Pen()
t.speed(0)
t.hideturtle()
turtle.bgcolor("black")
def draw_smiley(x,y):
t.penup()
t.setpos(x,y)
t.pendown()
# Face
t.pencolor("yellow")
t.fillcolor("yellow")
t.begin_fill()
t.circle(50)
t.end_fill()
# Left eye
t.setpos(x-15, y+60)
t.fillcolor("blue")