I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.
When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:
b = wx.Button(self, 10, "Default Button", (20, 20)) self.Bind(wx.EVT_BUTTON, self.OnClick, b) def OnClick(self, event): self.log.write("Click! (%d)\n" % event.GetId())
But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value?
It would greatly reduce copy & pasting the same code but with different callers.
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.
The first parameter represents the object raising the event. The second, called the event argument, contains information specific to the event, if any. For most events, the event argument is of type EventArgs, which does not expose any properties.
To pass one or more arguments to a procedure In the calling statement, follow the procedure name with parentheses. Inside the parentheses, put an argument list. Include an argument for each required parameter the procedure defines, and separate the arguments with commas.
Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.
You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.
b = wx.Button(self, 10, "Default Button", (20, 20)) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b) def OnClick(self, event, somearg): self.log.write("Click! (%d)\n" % event.GetId())
If you're out to reduce the amount of code to type, you might also try a little automatism like:
class foo(whateverwxobject): def better_bind(self, type, instance, handler, *args, **kwargs): self.Bind(type, lambda event: handler(event, *args, **kwargs), instance) def __init__(self): self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With