OO GUI programming style: assign widgets to instance attributes?
In my, admittedly limited, experience with OO GUI programming (mostly with JAVA and Tkinter), I've noticed that in some code all widgets are assigned to instance attributes, while in other code, few if any are.
For example, in A Simple Hello World Program from the Tkinter chapter of the python docs, both buttons are assigned to instance attributes of the Application class:
class Application(Frame):
...
def createW开发者_JAVA技巧idgets(self):
self.QUIT = Button(self)
...
self.hi_there = Button(self)
...
def __init__(self, master=None):
Frame.__init__(self, master)
...
self.createWidgets()
On the other hand, the Dialog Windows chapter of the Tkinter book defines a dialog support class with none of its widgets assigned to instance attributes:
class Dialog(Toplevel):
def __init__(self, parent, title = None):
Toplevel.__init__(self, parent)
...
body = Frame(self)
...
self.buttonbox()
...
...
def buttonbox(self):
...
box = Frame(self)
w = Button(box, ...)
...
w = Button(box, ...)
...
...
Question Statement
What are the pros/cons of each approach, and are there situations where it would make more sense to use one approach instead of the other?
My rule of thumb is simple: if you are going to need to reference it later, make it an attribute. If not, don't.
I'm not sure I can enumerate any pros or cons with that approach -- neither saving all references nor saving only the ones you need is particularly good or bad, it's mostly a matter of style.
That being said, however, making an attribute for a widget may imply it is used elsewhere. If it is not used elsewhere, people may make inferences about your code that are not true.
Many times you will not need to reference a widget after you add it to the window and wire it up with events; in those cases the widget would not end up as an attribute. Also, if the container is dynamic, you would not make the widget an attribute (since you wouldn't know in advance the widgets the object would have).
If the container is static and you know you need to reference the widget later, you can make it an object attribute; this will make references to the widget in other parts of the class clear and compact.
精彩评论