Event handling in wxPython

How can I pass an argument to an event handler in wxPython?

Here's my code:

    def close_handler(event):
        baz(foo)

    ...

    foo = 'bar'
    frame.Bind(wx.EVT_CLOSE, close_handler)

      

How do I pass a function foo to close_handler()

?

+2


source to share


2 answers


Do close_handler

create a second event handling function that uses foo

:

def close_handler(foo):
    return lambda event: baz(foo)

foo = 'bar'
frame.Bind(wx.EVT_CLOSE, close_handler(foo))

      

Here lambda event: baz(foo)

is an anonymous function that calls baz(foo)

, silently discarding the argument event

. Or you can pass it on baz

, if you want to: lambda event: baz(foo, event)

.



You can also write it without using lambda

like this:

def close_handler(foo):
    def event_handler(event):
        return baz(foo)

    return event_handler

      

+2


source


import functools

def close_handler(event, foo):
    baz(foo)

foo = 'bar'
func = functools.partial(close_handler, foo=foo)
frame.Bind(wx.EVT_CLOSE, func)

      

Or to save some space:



import functools

def close_handler(event, foo):
    baz(foo)

frame.Bind(wx.EVT_CLOSE, functools.partial(close_handler, foo='bar'))

      

+4


source







All Articles