Python turtle graphics onkey 函数使用数字键盘键的问题

Issue using num pad keys for Python turtle graphics onkey function

我在使用小键盘 1-9 键作为输入创建 turtle.onkey 命令时遇到问题。

我查看了源代码和文档,似乎作为参数的键来自 tkinker。我发现 a list of keys from the documentation there as well as this list,据我所知,小键盘上的数字“4”的参数应该是 "KP_4",但我的代码不会接受它。我已经为左箭头尝试了更传统的键,例如 "Left",这些似乎工作正常。我还查看了这里关于 pygame 的文档,认为它可能是相似的,但他们为小键盘 4 列出的那个也不起作用。 (是 K_KP4)

def player_move_left():
    x = player_char.xcor()
    x -= player_max_move
    player_char.setx(x)
turtle.onkey(player_move_left,"K_P4")

这应该取 x 坐标,减去移动量,然后将该数字应用于玩家变量的 x 坐标。

*第一个答案中提供的解决方案*

我的(OS X)系统不区分主键上的“4”和小键盘上的“4”,都移动了乌龟。但是,它确实区分了主键上的 "Return" 和小键盘上的 "KP_Enter",因此我将在我的示例代码中使用它:

from turtle import Screen, Turtle

player_max_move = 10

def player_move_left():
    x = player_char.xcor() - player_max_move

    player_char.setx(x)

screen = Screen()

player_char = Turtle()

screen.onkey(player_move_left, "KP_Enter")  # vs "Return"
screen.listen()

screen.mainloop()

尝试以上内容,看看您是否可以深入了解您的问题(例如,您是否遗漏了任何步骤?)