python - AttributeError: 'Application' 对象没有属性 'tk'

标签 python python-3.x tkinter attributeerror

我有以下脚本,它使用 Tkinter:

import tkinter as tk

class Application(tk.Frame):    

    def __init__(self, master):
        frame = tk.Frame(master)
        frame.pack

        self.PRINT = tk.Button(frame, text = 'Print', fg = 'Red', command = self.Print())
        self.PRINT.pack(side = 'left')    

        self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit())
        self.QUIT.pack(side = 'left')    

    def Print(self):
        print('at least somethings working')

root = tk.Tk()

b = Application(root)    
root.mainloop()

当我运行它时,出现以下错误:

AttributeError: 'Application' object has no attribute 'tk'

为什么我会收到此错误?

最佳答案

我在这里运行了你的脚本并得到了这个堆栈跟踪:

Traceback (most recent call last):
  File "t.py", line 23, in <module>
    b = Application(root)    
  File "t.py", line 15, in __init__
    self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit())
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1283, in quit
    self.tk.quit()
AttributeError: 'Application' object has no attribute 'tk'

错误消息出现在最后,但整个堆栈很重要!我们来分析一下。

显然,有一个对象,Application 的实例类,没有 tk属性。有道理:我们创建了这个类,但没有添加这个属性。

好吧,主循环期望存在一个属性!发生的事情是,我们的类(class)扩展了tkinter.Frame ,框架需要这个 tk属性。幸运的是,我们不必考虑如何创建它:由于所有框架都需要它,框架初始值设定项(其 __init__() 方法)知道如何设置此属性。

那么,我们要做的就是调用 tkinter.Frame我们自己的初始化器中的初始化器。这可以通过调用 __init__() 轻松完成。直接来自tk.Frame ,通过self变量:

tk.Frame.__init__(self, master)

整个脚本将是这样的,然后:

import tkinter as tk

class Application(tk.Frame):    

    def __init__(self, master):
        tk.Frame.__init__(self, master)

        frame = tk.Frame(master)
        frame.pack

        self.PRINT = tk.Button(frame, text = 'Print', fg = 'Red', command = self.Print())
        self.PRINT.pack(side = 'left')    

        self.QUIT = tk.Button(frame, text = 'Quit', fg = 'Red', command = self.quit())
        self.QUIT.pack(side = 'left')    

    def Print(self):
        print('at least somethings working')

root = tk.Tk()

b = Application(root)    
root.mainloop()

现在,您的脚本中还会有一些其他错误,您很快就会发现;)还有一些与多重继承相关的复杂问题可以解决 with the super() function 。尽管如此,这是您的第一个错误的解决方案。

关于python - AttributeError: 'Application' 对象没有属性 'tk',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50222747/

相关文章:

python-3.x - 使用 OpenCV 从图像中减去一条线

python - 不和谐.py |发出静音命令,无法获取成员名称

python - 给定一个列表,如何计算该列表中的项目?

Python 使用 Pandas 读取固定宽度文件,无需任何数据类型解释

python - 从python中的.txt文件中读取特殊字符

python - 检测 python 程序/函数/方法可以引发哪些异常

python - tkinter 字体中没有属性 "call"错误

python - 尝试保存 tkInter 比例的值

python - 如何确定按钮何时在 Tkinter 中发布?

python - Gunicorn:尝试启动 Flask 服务器时无法在 'app' 中找到属性 'wsgi'