检测上下文菜单的取消

时间:2019-06-27 08:10:12

标签: python wxpython

对于我的应用,我需要检测用户是否取消了上下文menu,例如使用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()

我该如何实现?显然,不可能绑定到Escape / Cancel事件。

1 个答案:

答案 0 :(得分:0)

您需要赶上事件wx.EVT_MENU_CLOSE。添加行:

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

使用您的OnContextMenu方法。

您应该注意,如果用户通过单击菜单外部来取消菜单,也会发送此事件。

您可以找到更多详细信息here