[英]Python turtle: check if a key is down
I want to be able to detect if a key is currently down.我希望能够检测到密钥当前是否已关闭。
I have found the turtle.onkey
and turtle.onkeypress
functions, however these don't work for me for two reasons:我找到了
turtle.onkey
和turtle.onkeypress
函数,但是这些对我不起作用有两个原因:
I want a boolean that is True
if the key is held down, or False
if the key is not held down.我想要一个 boolean 如果按键被按下则为
True
,如果按键未被按下则为False
。
You can't get that directly, but you can use a class that will follow the events regarding the keys that you want to be able to check:您无法直接获得该信息,但您可以使用 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
A little demo, the state of 'a' and 'b' will be printed each time you click in the window:一个小演示,每次点击 window 时都会打印出 'a' 和 'b' 的 state:
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()
If you want to follow the state of a bunch of keys, you could create their watchers like this:如果你想关注一堆键的 state,你可以像这样创建它们的观察者:
keys_to_watch = {'a', 'b', 'c', 'd', 'space']
watched_keys = {key: WatchedKey(key) for key in keys_to_watch}
and check individual keys with并检查各个键
b_pressed = watched_keys['b'].down
I found a solution.我找到了解决方案。 I just set it up to change a variable depending on whether the key is down
我只是将它设置为根据键是否按下来更改变量
def wdown():
global forward
forward=True
def wup():
global forward
forward=False
screen.onkeypress(wdown,"w")
screen.onkey(wup, "w")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.