Rahul
Rahul

Reputation: 177

super() in tkinter application

I am having trouble understanding this error.

In the below code,when I use tk.Frame everything works as intended. However if I use super(), I get thrown an AttributeError ('Application object has no attribute 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()

It is my understanding that super(Application,self).__init__() will call the the __init__ method that is bounded to the class followed by child in the instance's MRO, which is, the class tkinter.Frame in my situation.

I verified this by printing out Application.__mro__ and checking.

So my question if both super().__init__(self,parent) and tk.Frame.__init__(self,parent) are referring to the same __init__ method of class tkinter.Frame, why is one throwing an error and the other working fine? I suspect I have some misunderstanding in the way super() works.

Upvotes: 5

Views: 4999

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36662

Python 3 super does not require to pass self as an argument.

The following example illustrates the correct way to call super to initialize the parent class of a 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()

The reason is that the python core developers decided to simplify the use of super, and abstracted the passing of self to the underlying code that powers python.
more info

Upvotes: 5

Related Questions