使用python-libaray-wxpython为每个菜单单击显示不同的面板



python代码显示带有菜单按钮的菜单栏

import wx
#dashboard frame
class mainGUI(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self,parent,title=title,size=(1024,780))
self.initialise()
def initialise(self):
panel=wx.Panel(self)
menubar=wx.MenuBar()
#buttons for  menu
home=wx.Menu()
report=wx.Menu()
statics=wx.Menu()
data=wx.Menu()
chart=wx.Menu()
#appending button to the menubar
#here should be menu event handler for each panel to show       
menubar.Append(home,"Home")
menubar.Append(report,"report")
menubar.Append(statics,"statics")
menubar.Append(data,"data") 
menubar.Append(chart,"chart")
self.SetMenuBar(menubar)

每个面板的类都显示在这里#为每个菜单附加事件处理程序

self.Show(True)

要让代码识别点击了哪个菜单,需要添加:

self.Bind(wx.EVT_MENU_OPEN, self.OnMenu, menubar)

这将触发OnMenu方法。

在该方法中,您可以识别使用事件查询点击的菜单:

evt.Menu.Title

从那里您可以更改当前显示的面板。

import wx
class MainGUI(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(1024, 780))
self.initialise()
def initialise(self):
menubar = wx.MenuBar()
home = wx.Menu()
report = wx.Menu()
menubar.Append(home, "Home")
menubar.Append(report, "report")
self.Bind(wx.EVT_MENU_OPEN, self.OnMenu, menubar)
self.SetMenuBar(menubar)
def OnMenu(self, evt=None):
if evt.Menu.Title == 'Home':
print('Home menu clicked')
elif evt.Menu.Title == 'report':
print('report menu clicked')

class MainApp(wx.App):
def __init__(self):
wx.App.__init__(self)
main_window = MainGUI(None, title='My app')
main_window.Show()

def main():
app = MainApp()
app.MainLoop()

if __name__ == '__main__':
main()