tkinter 应用程序中的 super()

super() in tkinter application

我无法理解这个错误。

在下面的代码中,当我使用 tk.Frame 时,一切都按预期工作。但是,如果我使用 super(),则会抛出 AttributeError('Application 对象没有属性 tk')。

class Application(tk.Frame):
   def __init__(self,parent):
       tk.Frame.__init__(self,parent) <----- This works
       # super().__init__(self,parent) <------ This line throws an error
.
.
.

if __name__=='main':
  root=tk.Tk()
  Application(root).pack()
  root.mainloop()

据我了解,super(Application,self).__init__() 将调用绑定到 class 的 __init__ 方法,然后在实例的 MRO 中调用 child,即, class tkinter.Frame 在我的情况下。

我通过打印 Application.__mro__ 并检查验证了这一点。

所以我的问题是,如果 super().__init__(self,parent)tk.Frame.__init__(self,parent) 都指的是 class tkinter.Frame 的相同 __init__ 方法,为什么会抛出错误另一个工作正常吗?我怀疑我对 super() 的工作方式有一些误解。

Python 3 super 不需要将 self 作为参数传递。

以下示例说明了调用 super 以初始化小部件的父 class 的正确方法:

import tkinter as tk 


class Application(tk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        tk.Button(self, text='Super!', command=root.destroy).pack()


root = tk.Tk()
Application(root).pack()
root.mainloop()

原因是 python 核心开发人员决定简化 super 的使用,并将 self 的传递抽象为支持 python 的底层代码.
more info