|pythonware.com||products ::: library ::: search ::: daily Python-URL!|
More on widget references
In the second example, the frame widget is stored in a local variable named frame, while the button widgets are stored in two instance attributes. Isn't there a serious problem hidden in here: what happens when the __init__ function returns and the frame variable goes out of scope?
Just relax; there's actually no need to keep a reference to the widget instance. Tkinter automatically maintains a widget tree (via the master and children attributes of each widget instance), so a widget won't disappear when the application's last reference goes away; it must be explicitly destroyed before this happens (using the destroy method). But if you wish to do something with the widget after it has been created, you better keep a reference to the widget instance yourself.
Note that if you don't need to keep a reference to a widget, it might be tempting to create and pack it on a single line:
Button(frame, text="Hello", command=self.hello).pack(side=LEFT)
Don't store the result from this operation; you'll only get disappointed when you try to use that value (the pack method returns None). To be on the safe side, it might be better to always separate construction from packing:
w = Button(frame, text="Hello", command=self.hello) w.pack(side=LEFT)