Hi all,
When using wxPython in the past, I have always followed the strategy
of attaching the controls I create to self. I have generally erred on
the side of caution, and therefore attached many more items to self
than strictly required.
Lately, I have been experimenting with the opposite strategy:
Attaching as little as possible to self, and instead tracking controls
by ID (always using wx.NewId() to generate ID numbers, of course).
However, aside from having to type "self" less often, it is not clear
to me what the advantages and disadvantages of this strategy might be.
To clarify what I am talking about, here are some code snippets
(complete working example is attached).
Using the first strategy, I create a button and bind it to an event
handler like so:
self.button1 = wx.Button(self, wx.ID_ANY, 'Button 1')
self.Bind(wx.EVT_BUTTON, self.OnButton1, self.button1)
Using the second strategy, I work like so:
self.ID_BUTTON2 = wx.NewId()
button2 = wx.Button(self, self.ID_BUTTON2, 'Button 2')
self.Bind(wx.EVT_BUTTON, self.OnButton2, id = self.ID_BUTTON2)
The second strategy complicates the event handler a little bit,
requiring an extra line of code.
def OnButton1(self, event):
self.button1.SetLabel('Waaah!')
def OnButton2(self, event):
button = self.FindWindowById(self.ID_BUTTON2)
button.SetLabel('Ouch!')
Both methods seem to work equally well, but the second requires a
little extra code and frequent calls to FindWindowById. Do I gain
anything by using it? For example, but not attaching so many controls
to self, do I reduce my memory footprint somehow? Or, since all of
those data structures have to sit in memory somewhere anyway, does it
make no difference? When I get to a complicated GUI, is FindWindowById
going to create a noticeable drag on performance as compared to simply
referring to a class property?
I initially started experimenting in this manner to solve some sort of
inter-panel communication issue whose details I now forget. It seems
that pubsub is a much more elegant solution to that problem, so maybe
this is all moot anyway, but it remains a topic that has piqued my
interest if for no other reason than to better understand wxPython.
Thanks,
Alan
demo.py (980 Bytes)