newbie: binding args in callbacks
Edward K. Ream
edream at tds.net
Wed Jul 10 11:04:02 EDT 2002
> My suggestion:
>
> def makeCallback(self, val):
> def callback(self=self, val=val): return self.myCallback(val)
> return callback
>
> and then:
>
> b = Tk.Button(..., command=self.makeCallback(val) )
>
> You don't need the default-values trick in Python 2.2 -- so, if
> that's what you're using, it would be better to use, instead:
>
> def makeCallback(self, val):
> def callback(): return self.myCallback(val)
> return callback
I tried this, and indeed this does work on 2.2. Really. Thanks very
much.
> If you're insistent on using lambda (only sensible reason being that
> you made a bet about lambda being used here), you _can_, e.g. in 2.2:
>
> def makeCallback(self, val):
> return lambda: self.myCallback(val)
>
> but I think the nested-function approach is more readable.
This also works on 2.2.
This "extra" level of indirection is needed. The following does not
work:
for val in vals:
callback=lambda: self.myCallback(val) # or (val=val)
b = Tk.Button(..., command=callback)
All the callbacks get bound to a function with the last val in vals. I
have no idea why. Maybe you could explain?
BTW, the reason I really like Python is that someone like me with
limited knowledge can actually produce some real work. Anyway, thanks
again for your help!
Edward
--------------------------------------------------------------------
Edward K. Ream email: edream at tds.net
Leo: Literate Editor with Outlines
Leo: http://personalpages.tds.net/~edream/front.html
--------------------------------------------------------------------
More information about the Python-list
mailing list