I'm trying to add keyboard input to move python's turtles but without even pressing the assigned key the turtle moves as if I'm holding the assigned key.
What am I doing wrong?
My code is below:
# import
import turtle
# init screen, turtle
window = turtle.Screen()
turt = turtle.Turtle()
turt.speed(5)
def up():
turt.forward(10)
def left():
turt.left(10)
def right():
turt.right(10)
while True==True:
turtle.onkey(up(), "Up")
turtle.onkey(left(), "Left")
#turtle.onkey(right(), "Right")
# window await
turtle.listen()
window.mainloop()
Rather than calling screen.onkey(function(), "key")
you call screen.onkey(funtion, "key")
So
turtle.onkey(up(), "Up")
becomes
turtle.onkey(up, "Up")
In addition to @jll123567's excellent suggestion (+1) about passing, instead of calling, the event handler functions, you need to get rid of the while True==True:
loop and move its content up a level. An infinite loop like this keeps listen()
and mainloop()
from getting called so your events never get registered, nor handled. A complete solution:
from turtle import Turtle, Screen
def up():
turtle.forward(10)
def left():
turtle.left(10)
def right():
turtle.right(10)
# init screen, turtle
screen = Screen()
turtle = Turtle()
turtle.speed('normal')
screen.onkey(up, 'Up')
screen.onkey(left, 'Left')
screen.onkey(right, 'Right')
screen.listen()
screen.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.