Search code examples
wxpythoncontextmenupopupmenu

PopupMenu in wxPython with key press activated context menu items


I have a GUI that creates a PopupMenu when I right click on a ListCtrl, and I'm able to select items from the PopupMenu with a (left) mouse click. In addition to this functionality, I'd like the context menu items to be able to be selected with specific key presses (e.g. "C" for "Clear", "A" for "Clear All").

How can I do this?

A snippet to show the idea-

self.listcontrol=wx.ListCtrl(self, wx.NewId(), style = wx.LC_LIST|wx.LC_SINGLE_SEL)
self.listcontrol.Bind(wx.EVT_RIGHT_DOWN, self.OnFileRightDown)
...
def OnFileRightDown(self,e):
  men=wx.Menu()
  cmi = wx.MenuItem(men, wx.NewId(), 'Clear All...')
  men.AppendItem(cmi)
  self.Bind(wx.EVT_MENU, self.OnClearAll,cmi)
  self.PopupMenu(men,e.GetPosition())

I'd like to be able to press "A" when the context menu pops up to execute the OnClearAll method defined elsewhere.

I tried using an accelerator but couldn't get it to work.

Thank you.


Solution

  • Tried it out and learned something (tested on Win8/wxPython 2.9.5.1):

    Example popup:

    Mind the two different underline styles here. Both work with both the lowercase and uppercase letter.

    • Applying the Accelerator by accelerator entry:

      menu = wx.Menu()
      item = wx.MenuItem(menu, self.popupID1, "One\tO")
      acc = wx.AcceleratorEntry()
      acc.Set(wx.ACCEL_NORMAL, ord('O'), self.popupID1)
      item.SetAccel(acc)
      menu.AppendItem(item)
      

    Allows to get rid of the underscore.

    • Applying the accelerator by modifying the menu item string with &:

      menu.Append(self.popupID2, "Two\t&T")