Controls member-variables with wxDesigner style dialog functions

Hi there,

Here's a tiny trick I thought I should share with you.

I use wxDesigner, which generates a "dialog function", which is a function that populates a frame/dialog with controls. The problem is that the generated code doesn't create member variables for your code, so you have to use things like this:

class MyFrame(wx.Frame):

  def __init__(...):
    bla bla
    WxDesignerGeneratedFormFunc(self, True)

  def GetTheTextBoxControl(self):
    return self.FindWindowById( ID_TEXTBOX1 )

Creating Get***Control functions can be tedious (even with wxDesigner's help) and calling self.GetWhateverControl() is waaay to much typing :o), so instead I wrote this tiny descriptor:

class control(object):

   def __init__(self, id):
      self.id = id

   def __get__(self, obj, type=None):
      return obj.FindWindowById(self.id)

   def __set__(self, obj, val):
      raise AttributeError()

Now I can do this in my Frame/Dialog derived class:

class MyFrame(wx.Frame):

  def __init__(...):
    bla bla
    WxDesignerGeneratedFormFunc(self, True)

  textbox = control(ID_TEXTBOX1)
  btnOK = control(ID_OKBTN)
  btnCancel = control(ID_CANCELBTN)

which allows me to just do a regular property access ("self.textbox" or "frameinstance.btnOK") to get my control.

Arnar

Hello Arnar,

class MyFrame(wx.Frame):

def __init__(...):
   bla bla
   WxDesignerGeneratedFormFunc(self, True)

def GetTheTextBoxControl(self):
   return self.FindWindowById( ID_TEXTBOX1 )

If the default behavior of wxDesigner is to create IDs for every control and
keep them around in your code, I am afraid wxDesigner is far less good than
I thought. I have never used it, so I don't know its default behavior.
However, as Chris and many others have pointed out in the past, using IDs to
identify controls in the code may become a mess when you have a lot of
widgets. In my opinion (but this is just a personal coding style), you
should avoid IDs and use meaningful names for your non top-level widgets.
This is also the reason why I have abandoned Boa Constructor in favor of
wxGlade at the beginning... I don't know the status of Boa right now, so I
can't say anything. However, in the rare cases in which I use a GUI builder,
I always prefer those that force you to use sizers almost everywhere and
that do not assing an ID to every control.

Just my 2c.

Andrea.

"Imagination Is The Only Weapon In The War Against Reality."
http://xoomer.virgilio.it/infinity77