tkinter 应用程序中的 super()

Rah*_*hul 5 class tkinter super python-3.x

我无法理解这个错误。

在下面的代码中,当我使用时,tk.Frame一切都按预期工作。但是,如果我使用super(),我会抛出一个AttributeError(“应用程序对象没有属性 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()
Run Code Online (Sandbox Code Playgroud)

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

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

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

Reb*_*que 5

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

super下面的例子说明了调用初始化widget父类的正确方法:

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()
Run Code Online (Sandbox Code Playgroud)

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