I wanted to simplify the event loop by providing a function to call when the element would generate an event. This works because the 'key' of the elements can also be an object, in this case a newly created Event object. I provide an event handler function to be called, and the idea was that this was called with the value returned by the win.read().
This is my simple example:
import PySimpleGUI as sg
class Event:
def __init__(self, func):
self.handler = func
def inputHandler(value):
print (f"received {value}")
def buttonHandler(button):
print ('button was pressed')
def checkBoxHandler(checkbox):
print (f'check was set {checkbox}')
input = sg.Input('Hello', enable_events = True, readonly=False, key = Event(inputHandler))
check = sg.Checkbox('check this', enable_events = True, key = Event(checkBoxHandler))
button = sg.Button('a button', key = Event(buttonHandler))
# note: elements above can also simply be inserted in layout below
layout = [
[input],
[check],
[button],
]
win = sg.Window('testing function calls as events', layout)
while (True):
event, values = win.read()
if event == sg.WIN_CLOSED:
break
event.handler(values[event])
win.close()
This works as expected for the input and the checkbox. When pressing the button it bombs out with a KeyError on the values[].
I guess the button is not present in values[...] so a simple
if event in values:
...
might work (did not test)
But:
- would anybody think of something to make it universal?
- unrelated to the event loop, why would the values[buttonkey] not contain the pressed/released state?