I currently have a situation like this:
keyboard.on_press(Function1) keyboard.on_press_key(';', Function2) keyboard.on_press_key('/', Function3)
Through trial I’ve found that the on_press_key() events always happen first (and the logic of my program is dependent on it) but I have no idea why, or if it’s a hardware- or OS- specific thing that could be inconsistent and break if used on other systems (?).
I’ve tried searching but couldn’t find anything on this. Is there a reliable way to know the order in which the events are triggered, or force them to be triggered in a particular order?
Advertisement
Answer
Looking at the source code, the flow of control is as follows:
- keyboard.on_press adds an entry in the
handlers
object stored in the global_listener
obj. - keyboard.on_press_key adds an entry in the
nonblocking_keys
dict.
When a key event is raised, process
is called, which calls pre_process_event (itself calling all callbacks in the nonblocking_keys
dict) BEFORE calling the handlers.
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()
However this is just an implementation detail which might evolve with new versions, you’d better not rely on it. Could you for ex call Function1
in Function2
and Function3
?