Two naive Tkinter questions

Eric Brunel eric.brunel at pragmadev.N0SP4M.com
Mon Nov 3 12:21:24 EST 2003


Pierre Quentel wrote:
> When you define self.b1, instead of using "command=self.setcolor"  
> you can bind the event "click with left button" to a callback method 
> by:
> self.b1=Button(self, bg="red")
> self.b1.bind("<Button-1>",self.setcolor)

You shouldn't do that: the usual way buttons work is to run the associated 
command when the mouse button is pressed in it, then released in it too. Having 
the command run when the button is just clicked may seem awkward to many users. 
And emulating the way button usually work with bindings would be quite 
difficult, if not impossible.

> With this syntax, setcolor must be defined with an argument, which 
> is an instance of the class Event. This instance has a "widget" 
> attribute, so with event.widget you are sure to get the widget which 
> called the method. You define setcolor by :
> 
> def setcolor(self,event):
>     event.widget["bg"]="blue"
> 
> You can try to bind the other button to setcolor the same way. Then 
> if you want a different color for each button, define setcolor by :
> 
> def setcolor(self,event):
>    if event.widget is self.b1:
>        event.widget["bg"]="blue"
>    elif event.widget is self.b2:
>        event.widget["bg"]="green"

This actually works, but you'd really better get used to using lambda's or 
Callback classes: they're far more generic and will solve many problems that 
this approach can't.

HTH
-- 
- Eric Brunel <eric dot brunel at pragmadev dot com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com





More information about the Python-list mailing list