[wxPython-users] Binding with parameters?

Chris Mellon arkanes at gmail.com
Tue Jul 17 05:50:34 PDT 2007


On 7/17/07, Jarno Väyrynen <javayryn at mail.student.oulu.fi> wrote:
> Hi,
>
> I'm fairly new with wxPython, and I have managed to bind a button press with an
> event handler. What I cannot do is, I would like to pass a parameter to this
> event handler, and I have no idea how to do it.
>
>
> Here is my button and bind:
> ______________________________________________________________________________
> self.createConditionActionSetButton = wx.Button(self.panel_left, label="Create
> Condition - Action Set", pos=(0, 20), size=(200,20))
>                 self.Bind(wx.EVT_BUTTON, self.OnCreateConditionActionSet,
> self.createConditionActionSetButton)
>
>
> And here the function:
> def OnCreateConditionActionSet(self, evt, path):
>                 logfile = open(path, 'r+')
>                 print 'create c a set'
> _______________________________________________________________________________
>
> So I have another function that creates and saves a file and returns this
> "path", and I should somehow be able to pass this "path" further to the other
> function "OnCreateConditionActionSet", which is called by pressing equivalent
> button.
>

You wrap the function in another function. This is an example of
functional programming and the power of first class functions and
closures.

Example:
pth = self.CreateLogfile()
btn = self.CreateButton()
self.Bind(wx.EVT_BUTTON, lambda evt: self.OnCreateConditionActionSet(evt, pth))

Here the lambda is creating a new function object. Because it uses a
variable from the
enclosing scope, it's whats known as a closure. When called, the pth
variable in the lambda will be the value of pth in the enclosing
function.

Now, all that said, from what you've shown I don't think that this is
the best solution. Try using the wx.Log classes or the python standard
logging class instead of passing around a path to a logfile
everywhere.




More information about the wxpython-users mailing list