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

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

我有以下使用 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 class 的实例,没有 tk 属性。有道理:我们创建了这个class,我们没有添加这个属性。

好吧,主循环需要一个属性存在!发生的事情是,我们的 class 扩展了 tkinter.Frame,并且框架需要这个 tk 属性。幸运的是,我们不必考虑如何创建它:因为所有框架都需要它,框架初始化器(它的 __init__() 方法)知道如何设置这个属性。

那么,我们要做的就是在我们自己的初始化器中调用 tkinter.Frame 初始化器。这可以通过直接从 tk.Frame 调用 __init__(),传递 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。尽管如此,这是您第一个错误的解决方案。