Functions: There’s a Name for That 161
position to the location of that mouse click on the screen. The
setpos() function is already given to us in the turtle module, but
what if we want to create our own functions to handle events?
Say we want to build a program that lets the user move the turtle
on their screen by pressing the arrow keys instead of clicking the
mouse button. How would we do that?
First, we have to build functions for moving the turtle for
each arrow keypress on the keyboard, and then we have to tell the
computer to listen for those keys to be pressed. Let’s write a pro-
gram that will listen for the up (), left (), and right () keyboard
arrow keys and let the user move the turtle forward or turn left or
right with those keys.
Let’s define some functions—up(), left(), and right()—that
will move and turn the turtle:
def up():
t.forward(50)
def left():
t.left(90)
def right():
t.right(90)
Our first function, up(), moves the turtle forward 50 pixels.
The second, left(), turns the turtle left 90 degrees. Finally, right()
turns the turtle right 90 degrees.
To run each of these functions when the user presses the correct
arrow key, we have to tell the computer which function goes with
which key and tell it to start listening for keypresses. To set the
callback function for a keypress event, we use turtle.onkeypress().
This function usually takes two parameters: the name of the call-
back function (the event handler functions we created) and the
specific key to listen for. To connect each of the three functions to
its corresponding arrow key, we would write:
turtle.onkeypress(up, "Up")
turtle.onkeypress(left, "Left")
turtle.onkeypress(right, "Right")
The first line sets the up() function as the event handler for
"Up" arrow keypresses; the function (up) goes first, and "Up" is the
name of the up arrow key, . The same goes for the left and right