Search code examples
pythonwxpython

Detect cancellation of context menu


For my app I need to detect, if a user cancels a Context menu, for example with Escape key.

import  wx

class TestPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        wx.StaticText(self, -1, "Right Click for Context menu")
        self.Bind(wx.EVT_CONTEXT_MENU, self.OnContextMenu)

    def OnContextMenu(self, event):
        self.popupID1 = wx.NewId()
        self.popupID2 = wx.NewId()
        self.popupID3 = wx.NewId()

        self.Bind(wx.EVT_MENU, self.OnPopup, id=self.popupID1)
        self.Bind(wx.EVT_MENU, self.OnPopup, id=self.popupID2)
        self.Bind(wx.EVT_MENU, self.OnPopup, id=self.popupID3)

        #how to detect/bind event ...? to call OnPopupCanceled if menu is cancelled
        menu = wx.Menu()
        menu.Append(self.popupID1, "One")
        menu.Append(self.popupID2, "Two")
        menu.Append(self.popupID3, "Three")

        self.PopupMenu(menu)
        menu.Destroy()

    def OnPopup(self, event):
        print "Item Selected, event id: ", event.GetId()

    #this should be called, it user exits the menu through escape key
    def OnPopupCanceled(self, event):
        print "Popup Menu cancelled"

app = wx.App(False)
frame = wx.Frame(None)
TestPanel(frame)
frame.Show(True)
app.MainLoop()

How can I achieve that? Obviously there is no possibility to bind on an Escape/Cancel event.


Solution

  • You need to catch the event, wx.EVT_MENU_CLOSE. Add the line:

    self.Bind(wx.EVT_MENU_CLOSE, self.OnPopupCanceled)
    

    to your OnContextMenu method.

    You should notice that this event will also be sent if the user cancels the menu by clicking outside the menu.

    You can find more details here.