使用`turtle.onkey(function(),“key”)`关键事件似乎陷入困境

时间:2018-02-14 00:18:13

标签: python python-3.x turtle-graphics

我正在尝试添加键盘输入以移动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()

2 个答案:

答案 0 :(得分:3)

而不是致电screen.onkey(function(), "key"),而是致电screen.onkey(funtion, "key")

所以

turtle.onkey(up(), "Up")

变为

turtle.onkey(up, "Up")

答案 1 :(得分:1)

除了@ 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()