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