You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

wxPython导入实例化MainMenuBar类遇两类错误,求解决方案

问题分析与解决

第一个错误:RuntimeError: super-class __init__() of type MainMenuBar was never called

你定义的MainMenuBar继承了wx.Panel,但它的__init__方法里没有调用父类的初始化函数。wxPython的所有控件类都必须调用父类的__init__才能完成对象的正确初始化,否则就会抛出这个错误。

第二个错误:AttributeError: 'MainMenuBar' object has no attribute 'SetMenuBar'

SetMenuBar是wx.Frame类的专属方法,wx.Panel根本没有这个方法。你之前把MainMenuBar继承自wx.Panel是完全错误的方向——菜单属于窗口(Frame),而非面板(Panel),必须调整设计逻辑。


正确实现方案

我们把MainMenuBar改成专门负责创建菜单的工具类,不需要继承任何wx控件,只需要接收Frame实例作为参数,在类内完成菜单创建、事件绑定,最后调用Frame的SetMenuBar方法即可。

修改后的filemenu.py代码:

import wx

APP_EXIT = 1 

class MainMenuBar:
    def __init__(self, parent_frame):
        self.parent_frame = parent_frame
        self.create_file_menu()

    def on_quit(self, e):
        self.parent_frame.Close()
    
    def create_file_menu(self):
        menubar = wx.MenuBar()
        file_menu = wx.Menu()
        
        qmi = wx.MenuItem(file_menu, APP_EXIT, '&Quit\tCtrl+Q')
        # 注意:确保power-on.png在当前运行目录,或使用绝对路径,否则图片加载会报错
        qmi.SetBitmap(wx.Bitmap('power-on.png'))
        file_menu.Append(qmi)

        self.parent_frame.Bind(wx.EVT_MENU, self.on_quit, id=APP_EXIT)
        menubar.Append(file_menu, '&File')
        self.parent_frame.SetMenuBar(menubar)

修改后的主类代码:

import os
import wx
from wx.lib.agw.scrolledthumbnail import ScrolledThumbnail, Thumb, PILImageHandler
import filemenu

class MainFrameImageThumbnail(wx.Frame):
    def __init__(self):
        super().__init__(parent=None, title="Mockup", size=(1200,800))
        
        self.scroll = ScrolledThumbnail(self, 10, size=(200,1200))
        self.panel = wx.Panel(self)
        self.scroll.SetBackgroundColour((5,5,5))
        font = wx.Font(wx.FontInfo(10).Bold())
        self.scroll.SetCaptionFont(font)
        self.scroll.SetThumbOutline(4)
        self.scroll.SetDropShadow(False)
        self.scroll.SetSelectionColour(wx.Colour(120,80,255))
        
        # 传入当前Frame实例,直接创建并绑定菜单
        self.menu = filemenu.MainMenuBar(self)

app = wx.App(False)
frame = MainFrameImageThumbnail()
frame.Show(True)
app.MainLoop()

关键调整点说明

  1. 移除无效继承:MainMenuBar不再继承wx.Panel,作为普通类专注于菜单创建逻辑。
  2. 传递Frame实例:通过构造函数接收Frame对象,直接调用Frame的SetMenuBar方法完成菜单设置。
  3. 修正事件绑定对象:把菜单退出事件绑定到Frame上,因为Close()是Frame的方法,绑定到Panel会导致操作无效。

内容的提问来源于stack exchange,提问作者HotWheels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:41:19