Two naive Tkinter questions

Martin Franklin mfranklin1 at gatwick.westerngeco.slb.com
Mon Nov 3 04:22:23 EST 2003


On Sun, 2003-11-02 at 21:32, Andrew Koenig wrote:
> > In the specific example, you could just *know* that setcolor deals
> > with self.b1. In the more general example, you can create dynamic
> > callback functions:
> >
> >    self.b1 = Button(self, bg = "red",
> >              command = lambda: self.b1.config(bg="blue"))
> >
> > This uses a number of tricks: the lambda function has no arguments,
> > yet it uses self - so it is a nested function. Also, inside a lambda
> > function, you can have only expressions, so self.b1['bg']='blue' would
> > not be allowed. In the general case, and not assuming nested
> > functions, you would write
> >
> >   def createWidgets(self):
> >     def b1_setcolor(self=self):
> >       self.b1['bg']='blue'
> >     self.b1 = Button(self, bg = "red", command=b1_setcolor)
> 
> I worked out something similar, but I must confess that it appears
> needlessly complicated. I was hoping for a simpler solution, such as a
> variation of the "command" attribute that would cause its associated
> argument to be called with the button rather than its parent.
> 
> Your first suggestion, knowing that setcolor deals with self.b1, doesn't
> work with my application because I'm going to have lots of these buttons,
> and I want to be able to set their colors independently.
> 


For this I would use a callback class and it's __call__ method

(untested)

class Callback:
    def __init__(self, button, colour):
        self.button = button
        self.colour = colour


    def __call__(self):
        self.button.config(background = self.colour)





self.b1 = Button(self, background = "red")
self.b1.config(command = Callback(self.b1, "blue"))
self.b1.pack(.....)



Regards
Martin


-- 
Martin Franklin <mfranklin1 at gatwick.westerngeco.slb.com>






More information about the Python-list mailing list