You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

求助:tkinter模块报AttributeError,代码无法正常运行

解决tkinter中的AttributeError: module 'tkinter' has no attribute 'Tk__init__'错误

嘿,这个问题其实是个很容易疏忽的语法小错误,我来帮你搞定它!

错误原因分析

你写的tk.Tk__init__(self, *args, **kwargs)是错误的写法——Python里调用父类的构造函数,需要先指定父类(这里是tk.Tk),然后通过点.访问它的__init__方法,而不是把两个名字连在一起写。

另外你的代码里还有个拼写错误:continer.grid_rowconfigure(0,weight=1)里的变量名continer少了一个字母a,应该是container,这个也会导致后续报错,得一起修正。

修正后的代码

这里给你两种正确的写法:

写法1:直接调用父类的__init__方法

import tkinter as tk

class YourApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        # 修正父类构造函数的调用语法
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side='top', fill='both', expand=True)
        # 修正变量名拼写错误
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

写法2:使用super()更简洁(推荐)

Python 3+里更推荐用super()来调用父类方法,不用显式写出父类名称,代码更简洁:

import tkinter as tk

class YourApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        container = tk.Frame(self)
        container.pack(side='top', fill='both', expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

这样修改后,你的代码就能正常运行啦,不会再出现那个AttributeError了!

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

火山引擎 最新活动