2017-10-13 51 views
1

我有一個wx應用程序,其中主框架有幾個子面板。我想在主框架中有一個菜單欄,其中每個菜單都與一個面板相關聯。這意味着創建菜單項並將它們綁定到事件處理程序應該在單獨的面板中完成,而不是在主框架中完成。下面是一個小例子:wxPython:在子面板中填充菜單

import wx 


class myPanel1(wx.Panel): 
    def __init__(self, parent, menubar): 
     super().__init__(parent=parent) 

     menu = wx.Menu() 
     menuAction1 = menu.Append(wx.ID_ANY, 'Action1') 
     menuAction2 = menu.Append(wx.ID_ANY, 'Action2') 

     menubar.Append(menu, '&Actions') 

     # This does not work because the EVT_MENU is only seen by the main frame(?) 
     self.Bind(wx.EVT_MENU, self.onAction1, menuAction1) 
     self.Bind(wx.EVT_MENU, self.onAction2, menuAction2) 

    def onAction1(self, event): 
     print('Hello1') 

    def onAction2(self, event): 
     print('Hello2') 


class mainWindow(wx.Frame): 
    def __init__(self, *args, **kwargs): 
     super().__init__(*args, **kwargs) 

     self.menubar = wx.MenuBar() 
     # There are more panels in my actual program 
     self.panel1 = myPanel1(self, self.menubar) 

     sizer = wx.BoxSizer(wx.HORIZONTAL) 
     sizer.Add(self.panel1, flag=wx.EXPAND, proportion=1) 
     self.SetSizerAndFit(sizer) 

     self.SetMenuBar(self.menubar) 
     self.Layout() 


class myApp(wx.App): 
    def OnInit(self): 
     frame = mainWindow(parent=None, title='Title') 
     self.SetTopWindow(frame) 
     frame.Show() 
     return True 


if __name__ == '__main__': 
    app = myApp() 
    app.MainLoop() 

現在的問題是,myPanel1.onAction1不叫,因爲從主框架菜單事件不會傳播到子面板。 有沒有什麼乾淨的方法可以做到這一點?

回答

1

同時我自己找到了答案。這是因爲改變

self.Bind(wx.EVT_MENU, self.onAction1, menuAction1) 
myPanel1.__init__

self.GetParent().Bind(wx.EVT_MENU, self.onAction1, menuAction1) 

反正一樣簡單,感謝大家誰想過這個問題對他們的努力。