我正在尝试添加键盘输入来移动python的乌龟,但即使没有按下指定的键,乌龟也会移动,就像我按住指定的键一样。
我做错了什么?
我的代码如下:
# 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()发布于 2018-02-14 10:27:03
调用screen.onkey(funtion, "key")而不是调用screen.onkey(function(), "key")
所以
turtle.onkey(up(), "Up")变成了
turtle.onkey(up, "Up")发布于 2018-02-14 14:10:25
除了@jll123567关于传递而不是调用事件处理函数的出色建议(+1)之外,您还需要摆脱while True==True:循环并将其内容上移一级。像这样的无限循环可以防止listen()和mainloop()被调用,这样你的事件就永远不会被注册或处理。完整的解决方案:
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()https://stackoverflow.com/questions/48777798
复制相似问题