[Tkinter-discuss] Callbacks to classes
alan.gauld at btinternet.com
Mon May 23 10:27:59 CEST 2011
"Bob van der Poel" <bob at mellowood.ca> wrote
> > I was setting up a menu call back to a Class with code like:
> > Button(bf, text=txt, height=1, command=cmd).grid(column=c, row=0,
> > pady=5)
> I got some help over in comp.python on this. Apparently there was a
> change between 2.6 and 2.7. There are 3 easy solutions:
> 1. Use a function :)
> 2. Use lambda.
> 3. Use a new style class, ie:
> I've tried all three and they all work. I'm not sure what the best
> method is.
Using a class is very unusual and has several drawbacks.
The main one is that Tkinter calls the call-back object which
in the case of a class creates a new instance. So you are
constantly creating new objects to which you have no
reference so cannot call their methods - which is a
bit pointless! So any action you perform needs to be in
the init method. You can do more with class callbacks
if you store the objects somewhere, like a class variable
or global list but its all very unusual and only used for
special occasions such as rewinding history etc..
Using a functiion is good if you have the same code shared
by many events or if it takes parameters, although in that
case you also need...
A lambda is probably the most common, especially when
you really want to call another function. The lambda body
just executes the function passing whatever parameters
So I'd say the normal case would be a combination
of lambda and function and classes used very rarely,
more or less only when persistent actions are required.
Author of the Learn to Program web site
More information about the Tkinter-discuss