wxpopupmenu with varying sets of menu items

C M,

I think I got it right this time. However, it's probably more convoluted that it needs to be. Hopefully you can understand my goofy idea of doing this and refactor it or just plain rewrite it so it's a little clearer.

I've attached the code. The only changes I made were to the following two methods:

<code>

def mypopupmenu(self):

    menu = wx.Menu()

    #A dict to access menu titles by ID--will be used in event handler
    self.menu_title_by_id = {}
    keys = self.menu_titles.keys()
    
    for key in keys:
        self.menu_title_by_id[wx.NewId()] = key

    #make the menu
    keys = self.menu_title_by_id.keys()
    keys.sort()
    for key in keys:
        title = self.menu_titles[self.menu_title_by_id[key]]
        popID = key
        item = wx.MenuItem(menu, popID, title)
        menu.AppendItem(item)

        #bind to a single event handler
        self.Bind(wx.EVT_MENU, self.OnPopupMenu, id=key)

    self.PopupMenu( menu)

def OnPopupMenu(self,event):
    title = self.menu_titles[self.menu_title_by_id[ event.GetId() ]]
    print title

</code>

I apologize for being so confusing and dense.

Mike

menu_items.py (2.55 KB)

Thanks a lot, Mike, I really appreciate it and it is working now.
However I'm not totally clear I understand it yet, so I will play with
it for awhile and try to understand it (I'm a little lost in the
multiple dicts, keys, lists, etc.) and may have a question tomorrow.
Thanks again!

···

On Fri, Apr 25, 2008 at 10:22 PM, Mike Driscoll <mdriscoll@co.marshall.ia.us> wrote:

C M,

I think I got it right this time. However, it's probably more convoluted that it needs to be. Hopefully you can understand my goofy idea of doing this and refactor it or just plain rewrite it so it's a little clearer.

I've attached the code. The only changes I made were to the following two methods:

<code>

def mypopupmenu(self):

    menu = wx.Menu()

    #A dict to access menu titles by ID--will be used in event handler
    self.menu_title_by_id = {}

    keys = self.menu_titles.keys()

    for key in keys:
        self.menu_title_by_id[wx.NewId()] = key

    #make the menu
    keys = self.menu_title_by_id.keys()

    keys.sort()
    for key in keys:
        title = self.menu_titles[self.menu_title_by_id[key]]
        popID = key

        item = wx.MenuItem(menu, popID, title)
        menu.AppendItem(item)

        #bind to a single event handler
        self.Bind(wx.EVT_MENU, self.OnPopupMenu, id=key)

    self.PopupMenu( menu)

def OnPopupMenu(self,event):
    title = self.menu_titles[self.menu_title_by_id[ event.GetId() ]]
    print title

</code>

I apologize for being so confusing and dense.

Mike