views:

138

answers:

2

How to 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 to pass foo to close_handler() function?

+1  A: 

Have 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 event argument. Or you could pass it to baz if you wanted: lambda event: baz(foo, event).

You could also write this without using lambda like so:

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

    return event_handler
John Kugelman
+3  A: 
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 conserve some space:

import functools

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

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