Two naive Tkinter questions

Andrew Koenig ark at acm.org
Sun Nov 2 16:32:12 EST 2003


> 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.

>
> > 2) The window in which these buttons appear is the wrong size, and does
not
> > depend on the height and width given to self.place in __init__.  Yet the
> > height and width arguments do something, because if I set width to 75,
it
> > cuts off half the right-hand button.  How do I say how large I want the
> > window to be?
>
> The problem is that there is another toplevel widget around your
> frame; the frame itself has the size you have specified. You could
> either use Toplevel instead of Frame as a base, or you could adjust
> the size of the root window, e.g. through
>
> app.master.wm_geometry("100x50")

Gotcha -- thanks.






More information about the Python-list mailing list