问题描述
我目前有这样的情况:
keyboard.on_press(Function1)
keyboard.on_press_key(';',Function2)
keyboard.on_press_key('/',Function3)
通过试用,我发现on_press_key()事件始终总是首先发生(并且程序的逻辑依赖于此),但我不知道为什么,或者这是否是特定于硬件或操作系统的事情不一致并在其他系统上使用时会中断(?)。
我尝试搜索,但找不到任何东西。是否存在一种可靠的方式来知道事件的触发顺序,或者强制事件以特定顺序触发?
解决方法
看一下源代码,控制流程如下:
- keyboard.on_press在存储在全局
handlers
obj中的_listener
对象中添加一个条目。 - keyboard.on_press_key在
nonblocking_keys
字典中添加一个条目。
引发键事件时,将调用process
,它会在调用处理程序之前先调用pre_process_event(自身会调用nonblocking_keys
字典中的所有回调)。
def process(self):
"""
Loops over the underlying queue of events and processes them in order.
"""
assert self.queue is not None
while True:
event = self.queue.get()
if self.pre_process_event(event):
self.invoke_handlers(event)
self.queue.task_done()
但是,这只是一个实现细节,可能会随新版本一起发展,您最好不要依赖它。您可以在Function1
和Function2
中致电Function3
吗?