Python乌龟:检查按键是否按下

时间:2019-11-09 15:01:50

标签: python turtle-graphics

我希望能够检测钥匙当前是否按下。

我找到了turtle.onkeyturtle.onkeypress函数,但是由于两个原因,这些函数对我不起作用:

  1. 它们仅在按下或释放键时触发。
  2. 它们在运行时调用一个函数。

我想要一个布尔值,如果按住该键,则为True,如果不按住该键,则为False

2 个答案:

答案 0 :(得分:2)

您不能直接获得它,但是可以使用一个类,该类将跟随与您要检查的键有关的事件:

import turtle

class WatchedKey:
    def __init__(self, key):
        self.key = key
        self.down = False
        turtle.onkeypress(self.press, key)
        turtle.onkeyrelease(self.release, key)

    def press(self):
        self.down = True

    def release(self):
        self.down = False

# You can now create the watched keys you want to be able to check:
a_key = WatchedKey('a')
b_key = WatchedKey('b')

# and you can check their state by looking at their 'down' attribute
a_currently_pressed = a_key.down

一个小示例,每次您在窗口中单击时,都会打印“ a”和“ b”状态:

def print_state(x, y):
    print(a_key.down, b_key.down)

screen = turtle.Screen()
screen.onclick(print_state)

turtle.listen()
turtle.mainloop()
turtle.done()

如果您想遵循一堆键的状态,则可以这样创建他们的观察者:

keys_to_watch = {'a', 'b', 'c', 'd', 'space']

watched_keys = {key: WatchedKey(key) for key in keys_to_watch}

并使用

检查单个键
b_pressed = watched_keys['b'].down

答案 1 :(得分:0)

我找到了解决方案。我只是将其设置为根据键是否按下来更改变量

def wdown():
    global forward
    forward=True
def wup():
    global forward
    forward=False



screen.onkeypress(wdown,"w")
screen.onkey(wup, "w")