我正在将Python 3.7与wxPython 4.0.4结合使用。当我只想要一个可单击的项目时,menuBar有问题。这是一个菜单栏,其中附加了菜单对象,但菜单对象中没有菜单项。没有下拉列表,也没有要绑定的ID。 menuBar对象使用onClick事件。我只想检测何时单击“运行”项。有什么办法赶上这个事件吗?
答案 0 :(得分:0)
真正的答案应该是,在您的Run
菜单中添加一个名为Run
的菜单项,因为这使用户可以选择运行该功能,而不是通过单击功能来意外运行它。菜单栏,答案是可以的。
Bind
到事件wx.EVT_MENU_OPEN
import wx
import wx.stc
class MyApp(wx.App):
def OnInit(self):
self.frame = MenuFrame(None, title="Menus and MenuBars")
self.SetTopWindow(self.frame)
self.frame.Show()
return True
ID_READ_ONLY = wx.NewId()
class MenuFrame(wx.Frame):
def __init__(self, *args, **kwargs):
super(MenuFrame, self).__init__(*args, **kwargs)
# Attributes
self.panel = wx.Panel(self)
self.txtctrl = wx.stc.StyledTextCtrl(self.panel,
style=wx.TE_MULTILINE)
# Layout
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(self.txtctrl, 1, wx.EXPAND)
self.panel.SetSizer(sizer)
self.CreateStatusBar() # For output display
# Setup the Menu
menub = wx.MenuBar()
# File Menu
filem = wx.Menu()
filem.Append(wx.ID_NEW, "New")
filem.Append(wx.ID_OPEN, "Open")
filem.Append(wx.ID_SAVE, "Save")
filem.Append(wx.ID_SAVEAS, "Save_As")
menub.Append(filem, "&File")
# Edit Menu
editm = wx.Menu()
editm.Append(wx.ID_UNDO, "Undo")
editm.Append(wx.ID_REDO, "Redo")
editm.Append(wx.ID_COPY, "Copy")
editm.Append(wx.ID_CUT, "Cut")
editm.Append(wx.ID_PASTE, "Paste")
editm.Append(wx.ID_SELECTALL, "SelectAll")
editm.AppendSeparator()
editm.Append(ID_READ_ONLY, "Read Only",
kind=wx.ITEM_CHECK)
menub.Append(editm, "Edit")
# History Menu
historym = wx.Menu()
historym.Append(wx.ID_PREVIEW, "Recent")
menub.Append(historym, "&History")
# Help Menu
helpm = wx.Menu()
helpm.Append(wx.ID_HELP_INDEX, "Hint")
helpm.Append(wx.ID_ABOUT, "About")
menub.Append(helpm, "&Help")
# Run Menu
runm = wx.Menu()
menub.Append(runm,"&Run")
self.SetMenuBar(menub)
# Event Handlers
self.Bind(wx.EVT_MENU, self.OnMenu)
self.Bind(wx.EVT_MENU_OPEN, self.OnMenu)
def OnMenu(self, event):
"""Handle menu clicks"""
evt_id = event.GetId()
if evt_id == 0:
obj = event.GetMenu()
if obj.GetTitle() == "&Run":
self.txtctrl.AddText('Running program\n')
else:
self.txtctrl.AddText("Menu item "+str(evt_id)+" selected\n")
if __name__ == "__main__":
app = MyApp()
app.MainLoop()
您可以选择: