Python 龟键侦听器无响应

Python turtle key listener unresponsive

所以我对 python 图形比较陌生。我正在松散地遵循 space 入侵者的教程,但我无法让关键的听众工作。任何想法为什么?

import turtle
import os
window = turtle.Screen()
player = turtle.Turtle()
move = 15


# sets up the window, background color and player sprite
def setup():
    window.bgcolor("black")
    window.title("Space Invaders")

    player.color("red")
    player.shape("triangle")
    player.penup()
    player.speed(0)
    player.setposition(0, -250)
    player.setheading(90)


# controls left and right movement
def move_left():
    player.setx(player.xcor() - move)
    print("left")


def move_right():
    player.setx(player.xcor() + move)
    print("right")


if __name__ == "__main__":
    setup()
    window.onkey(move_left(), "Left")
    window.onkey(move_right(), "Right")
    window.listen()
    turtle.mainloop()

这只是一个猜测,因为我不是乌龟专家,但可能是两者之一

1- 您应该在 windows.onkey() 方法之前使用 windows.listen() 方法。

2- 您应该添加一个始终设置为 true 的 while 循环(但我想这就是 turtle.mainloop()) 的作用?

不是 100% 确定,但我认为你应该参加

window.onkey(move_left(), "Left")
window.onkey(move_right(), "Right")

在 if 语句之外,因为这可能是问题所在。 如果这不起作用,请尝试像这样摆脱 ()...

window.onkey(move_left, "Left")
window.onkey(move_right, "Right")

如果这不起作用,请将设置函数内的所有内容都取出来。

我真的只能说这些了,但如果所有这些都失败了,请更仔细地按照教程进行操作。我还发现这两件事可能会有很大帮助。 Python, Turtle Graphics, Key bindings 还有这个 Make key bindings work for Space Invaders game