Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

162 Chapter 7


arrow keypresses. The final step is telling the computer to begin
listening for keypresses, which we do with this command:

turtle.listen()

We need this last line for a couple of reasons. First, unlike
with mouse clicks, simply pressing a key doesn’t ensure that our
turtle window will receive the keypress. When you click a window
on your desktop, that window moves to the front and receives the
focus, meaning that window will receive input from the user. When
you click the mouse on the turtle window, it automatically makes
that window the focus of the screen and of any mouse events that
follow. With the keyboard, though, just pressing keys doesn’t make
a window receive those keypresses; the turtle.listen() command
makes sure our turtle’s window is the focus of the desktop so that
it will be able to hear keypresses. Second, the listen() command
tells the computer to start handling keypress events for all keys
that we connected to functions with the onkeypress() function.
Here’s the complete ArrowDraw.py program:
ArrowDraw.py

import turtle
t = turtle.Pen()
t.speed(0)
u t.turtlesize(2,2,2)
def up():
t.forward(50)
def left():
t.left(90)
def right():
t.right(90)
turtle.onkeypress(up, "Up")
turtle.onkeypress(left, "Left")
turtle.onkeypress(right, "Right")
turtle.listen()

At u, the only new line in ArrowDraw.py, we make the
turtle arrow twice as big, and give it a thicker outline with
t.turtlesize(2,2,2). The three parameters are the horizontal
stretch ( 2 means to make it twice as wide), the vertical stretch
( 2 times as tall), and the outline thickness ( 2 pixels thick).
Figure 7-5 shows the result.
Free download pdf