Skip to content Skip to sidebar Skip to footer

Python, Turtle Graphics, Key Bindings

I'm trying to figure out a way to make it to when I hold down a key the player will constantly move, or just have the player move forward constantly with just turtle graphics, (I d

Solution 1:

You can fix it simply by adding wn to start of

wn.onkey(forward, 'Up')
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')

wn.listen()
wn.mainloop()

I hope this helps!

Solution 2:

I recommend you read this post on repeating key events and first determine whether your operating system provides key repeat and whether you can/want to adjust that and/or how to turn it off to implement your own. That link includes code to implement your own key repeat behavior in turtle.

I've reworked your code below and the keys repeat fine for me because my operating system (OSX) implements key repeat:

from turtle import Turtle, Screen

# Setup Screen
wn = Screen()
wn.setup(700, 700)
wn.title('white')
wn.bgcolor('black')

# Create Player
player = Turtle('triangle')
player.speed('fastest')
player.color('white')
player.penup()

def forward():
    player.forward(20)

def left():
    player.left(90)

def right():
    player.right(90)

wn.onkey(forward, 'Up')
wn.onkey(left, 'Left')
wn.onkey(right, 'Right')

wn.listen()
wn.mainloop()

In OSX I can control the rate (and turn it off) in the Keyboard panel of Systems Preferences. Look into what your OS provides.

Some programming notes: avoid importing the same module two different ways, this always leads to confusion. If you find you're getting interference between keyboard events at high repetition rates consider the following for all three event handlers:

defforward():
    wn.onkey(None, 'Up')  # disable event in handler
    player.forward(20)
    wn.onkey(forward, 'Up')  # reenable event

Post a Comment for "Python, Turtle Graphics, Key Bindings"