[Tkinter-discuss] No Parameters fo Callback functions?

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Fri Nov 4 11:53:54 CET 2005


Fredrik Lundh wrote:
> Martin Franklin wrote:
> 
> 
>>The 'standard alternative' to lambda is to use a callback class
>>like so :)
>>
>>class Callback:
>>     def __init__(self, checkbutton, action):
>>         self.checkbutton = checkbutton
>>         self.action = action
>>
>>     def __call__(self):
>>         self.action(self.checkbutton)
> 
> 
> I strongly recommend using local function objects instead; the code

Indeed, I should have said one of the standard alternatives :)
for whatever reason I seem to find the callback class more readable 
perhaps I just came across it first...

> is straightforward, they're cheap to create, and they give you a lot
> more flexibility the day you need to add more functionality to your
> callbacks.
> 
>     def callback():
>         self.actionFunction("checkButton1")
>     cb1 = Checkbutton(self, command=callback)
> 
>     def callback():
>         self.actionFunction("checkButton2")
>     cb2 = Checkbutton(self, command=callback)
> 
> or, in a loop
> 
>     # create ten buttons
>     for i in range(10):
>         def callback(i=i): # <-- note: bind to value, not name
>             self.actionFunction("checkButton%d" % i)
>         cb = Checkbutton(self, text="Button %d" % i, command=callback)
>         cb.pack()
> 
> (the i=i construct is used to bind to the *current* value of the i
> variable, rather than whatever value it has when you leave the
> current scope)
> 
> </F>



More information about the Tkinter-discuss mailing list