wxPython menu creation refactoring

Nick Craig-Wood nick at craig-wood.com
Thu Apr 30 10:30:04 CEST 2009


alex <alecla at bluewin.ch> wrote:

>  I am still trying to refactor a simple GUI basing on an example in
>  "wxPython In Action", "Listing 5.5 A refactored example" where the
>  menue creation is "automatized".  I understand the problem (each
>  second for loop in "def createMenuData (self)" creates a distinct
>  menu) but I tried now for some evenings and do not get to any
>  possible solution.  I am still learning Python and hope to use it
>  as a front end for my Fortran programs (subprocess and ctypes work
>  very well...)  with the aim of increasing the Python part (text
>  parsing) in the future.  The following code shows the problem and
>  works out of the DOS box.  Any help would be greatly apreciated.
[snip]
>     def createMenu(self, itemLabel, itemHandler):
>         menu = wx.Menu()
>         menuItem = menu.Append(wx.NewId(), itemLabel)
>         self.Bind(wx.EVT_MENU, itemHandler, menuItem)
>         return menu
> 
>      def createMenuData(self):
>          menuBar = wx.MenuBar()
>          for eachMenuData in self.menuData():
>              menuLabel = eachMenuData[0]
>              for eachLabel, eachHandler in eachMenuData[1:]:
>                  menuBar.Append(self.createMenu(eachLabel,
>  eachHandler), menuLabel)
>          self.SetMenuBar(menuBar)

I think you want this instead

    def createMenuData(self):
        menuBar = wx.MenuBar()
        for eachMenuData in self.menuData():
            menuLabel = eachMenuData[0]
            submenu = wx.Menu()
            for eachLabel, eachHandler in eachMenuData[1:]:
                item = wx.MenuItem(submenu, -1, eachLabel)
                submenu.AppendItem(item)
                self.Bind(wx.EVT_MENU, eachHandler, item)
            menuBar.Append(submenu, menuLabel)
        self.SetMenuBar(menuBar)

That is the way I normally do it anyway!

You create the submenu as a seperate menu then attach it to the
menuBar with the label.

Note there is a wxpython list also which you may get more help in!

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list