P
P
pgamesorg2020-03-22 14:36:06
Python
pgamesorg, 2020-03-22 14:36:06

How to correctly catch active events in a thread?

Let's say for each event something should happen.

Let's say there are 5 events:

[ 1, 2, 3, 4, 5 ]

And each of the events has a function that changes the background color.

Question:
How to properly bind events to the functions to which they relate, i.e. when event 3 occurs, the window color should turn red and when event 1 occurs - white, etc.

Or you can add buttons to the class a list of callbacks and the connect method, which will have some callback as an argument and, on pressing the button, we run through this list and call each callback?

from collections import defaultdict

LISTENERS = defaultdict(list)



event = queue.get()
for listener in LISTENERS[event.__class__]:
  listener(event)






def register_listener(event_cls):
    def deco(func):
        LISTENERS[event_cls].append(func)
        return func
    return deco







@register_listener(ButtonClickedEvent)
def on_click(event: ButtonClickedEvent):
  pass

@register_listener(ChangeValue)
def on_click(event: ChangeValue):
  pass

@register_listener(SetSize)
def on_click(event: SetSize):
  pass

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question