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

Tkinter出现AttributeError:'_tkinter.tkapp'无button_creation属性问题咨询

问题原因

核心错误出在菜单命令的调用逻辑上:
在MenuBar类的fileMenu.add_command中,你使用CustomWidgets.openNewWindow(parent)直接调用类的未绑定方法,此时parent(也就是Tk()实例,即_tkinter.tkapp对象)会被当作openNewWindow的第一个参数self传入。

这就导致openNewWindow方法里的self不再是CustomWidgets的实例,而是tkinter的主窗口对象——这个对象没有定义button_creation方法,自然会抛出AttributeError。

修复方案

提供两种可行的修复方式:

方式一:传递CustomWidgets实例给MenuBar

修改CustomWidgets的初始化方法,将自身实例传入MenuBar:

def __init__(self):
    self.root=Tk()
    menubar = MenuBar(self.root, self)  # 传入当前CustomWidgets实例
    self.root.config(menu=menubar)

同步修改MenuBar的实现,接收并保存实例,调用实例方法:

class MenuBar(Menu):
    def __init__(self, parent, widget_instance):
        Menu.__init__(self, parent)
        self.widget_instance = widget_instance
        fileMenu = Menu(self, tearoff=False)
        self.add_cascade(label="Menu",underline=0, menu=fileMenu)
        # 调用实例的openNewWindow方法
        fileMenu.add_command(label="Email Configuration", underline=1, command=self.widget_instance.openNewWindow)

方式二:直接绑定实例方法到菜单命令

如果不想改动MenuBar的结构,可以调整CustomWidgets的初始化逻辑,直接把自身的openNewWindow方法绑定到菜单命令:

def __init__(self):
    self.root=Tk()
    menubar = MenuBar(self.root)
    # 给菜单命令绑定当前实例的openNewWindow方法
    menubar.fileMenu.add_command(label="Email Configuration", underline=1, command=self.openNewWindow)
    self.root.config(menu=menubar)

同时需要把MenuBar中的fileMenu改为实例属性,让外部可以访问:

class MenuBar(Menu):
    def __init__(self, parent):
        Menu.__init__(self, parent)
        self.fileMenu = Menu(self, tearoff=False)  # 改为实例属性
        self.add_cascade(label="Menu",underline=0, menu=self.fileMenu)
补充说明
  • Python中,类的方法通过实例调用时,会自动将实例作为第一个参数(self)传入,这是绑定方法;直接通过类调用方法时,需要手动传入self参数,若传入的不是类的实例,就会出现属性不匹配的问题。
  • 你的代码正是错误地将tkinter窗口对象当作CustomWidgets实例传入,才导致找不到目标方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:20:20