Arguments for button command via Tkinter?

Francesco Bochicchio bockman at virgilio.it
Tue Nov 1 09:35:57 CET 2005


Il Mon, 31 Oct 2005 19:23:18 +0000, Steve Holden ha scritto:

> Francesco Bochicchio wrote:
>> Il Mon, 31 Oct 2005 06:23:12 -0800, dakman at gmail.com ha scritto:
>> 
>> 
>>>And yet the stupidity continues, right after I post this I finnally
>>>find an answer in a google search, It appears the way I seen it is to
>>>create a class for each button and have it call the method within that.
>>>If anyone else has any other ideas please tell.
>> 
>> 
>> This is  how I do it: Supposing I have three buttons b1, b2 and b3, and I
>> want for each button to call the same callback with, as argument, the
>> button itself:
>> 
>> 
>> def common_callback(button):
>> 	# callback code here
>> 
>> 
>> class CallIt(objetc):
>> 	def __init__(function, *args ):
>> 		self.function, self.args = function, args
>> 	def __call__(self, *ignore):
>> 		self.function(button, *self.args)
>> 
>> b1['command']= CallIt(common_callback, b1)
>> b2['command']= CallIt(common_callback, b2)
>> b3['command']= CallIt(common_callback, b3)
>> 
>> This way you need only one class (a sort of custom callable) and
>> its instances gets called by Tkinter and in turn calls your
>> callback with the proper arguments.
>> 
> I don't see why this is preferable to having the callback as a bound 
> method of the button instances. What's the advantage here? It looks 
> opaque and clunky to me ...
> 
> regards
>   Steve

I'm not saying that my method is better or even 'preferable'. Just
different.

The reason I came up this approach (years ago) is because I was used to
other toolkits that always pass the widget as argument of the callback. So
this was a fast solution to 'normalize' Tkinter with respect to what I
perceived (and still do) as a limitation. As a bonus, you can also pass to
the callback as many other arguments as you want.
Another reason is that my basic approach to coding GUI is to use a class
for each window. To put the code to handle button callbacks in a separate
class feels to me a bit too much dispersive and potentially cumbersome if
callback code has to interact with other window elements (although in
Python nothing is impossible).

Ciao
-----
FB


why I sometime 




More information about the Python-list mailing list