Python 乌龟:检查按键是否按下
Python turtle: check if a key is down
我希望能够检测当前是否有键按下。
我找到了 turtle.onkey
和 turtle.onkeypress
函数,但是这些函数对我不起作用,原因有二:
- 它们仅在按下或释放键时触发。
- 当你 运行 他们调用一个函数。
我想要一个布尔值,如果按键被按下,则为 True
,如果按键未被按下,则为 False
。
我找到了解决办法。我只是将其设置为根据按键是否按下来更改变量
def wdown():
global forward
forward=True
def wup():
global forward
forward=False
screen.onkeypress(wdown,"w")
screen.onkey(wup, "w")
您无法直接获取该信息,但您可以使用 class 来跟踪与您希望能够检查的密钥相关的事件:
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
一个小demo,每次点击window:
都会打印'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
我希望能够检测当前是否有键按下。
我找到了 turtle.onkey
和 turtle.onkeypress
函数,但是这些函数对我不起作用,原因有二:
- 它们仅在按下或释放键时触发。
- 当你 运行 他们调用一个函数。
我想要一个布尔值,如果按键被按下,则为 True
,如果按键未被按下,则为 False
。
我找到了解决办法。我只是将其设置为根据按键是否按下来更改变量
def wdown():
global forward
forward=True
def wup():
global forward
forward=False
screen.onkeypress(wdown,"w")
screen.onkey(wup, "w")
您无法直接获取该信息,但您可以使用 class 来跟踪与您希望能够检查的密钥相关的事件:
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
一个小demo,每次点击window:
都会打印'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