Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass additional arguments to an event callback?

Is it possible to pass additional arguments to an event callback?

For example, if my event binding looked like this;

self.Bind(wx.EVT_BUTTON, self.do_something, self.button) 

How could I pass the arguments to my method?

self.do_something(self,event,arguments):
    """do something with arguments"""
    pass
like image 242
Sheldon Avatar asked Jun 28 '12 13:06

Sheldon


People also ask

Is it possible to pass an additional parameter to an event handler?

Of course you can. (If it was the event you define yourself, you would need to create you own event arguments class where you would put all the information you need.

How do I pass a parameter to an event handler or callback?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

Can a callback function have arguments?

Callback Functions A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.


1 Answers

Use functools.partial, or in the general case a lambda expression.

The partial form would be

functools.partial(self.do_something, args)

Note that in this case the event argument will be passed at the end of the argument list. The equivalent lambda form is:

lambda event: self.do_something(args, event)
like image 151
ecatmur Avatar answered Nov 14 '22 21:11

ecatmur