wxPython:在子面板中填充菜单

2024-04-19 22:44:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个wx应用程序,其中主框架有几个子面板。我想在主框架中有一个菜单栏,每个菜单都与一个面板相关联。这意味着菜单项的创建和绑定到事件处理程序应该在单独的面板中完成,而不是在主框架中。下面是一个简单的例子:

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,因为主框架中的菜单事件不会传播到子面板。 有什么好办法吗?你知道吗


Tags: self框架面板initdefframeclassparent