Two naive Tkinter questions

Martin v. Löwis martin at v.loewis.de
Sun Nov 2 15:34:18 EST 2003


"Andrew Koenig" <ark at acm.org> writes:

> 1) When I run this program, it displays two buttons.  When I click the
> button on the left, I would like the color of that button to change from red
> to blue.  This code is obviously the wrong way to accomplish this, because
> when setcolor is called, it gets the button's parent, not the button itself.
> How do I arrange for setcolor to get the right object?

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)

> 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")

HTH,
Martin





More information about the Python-list mailing list