Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use super() when subclassing Tkinter widgets? [duplicate]

Trying to create Tkinter window using super(). I get this error:

TypeError: super() argument 1 must be type, not classobj

Code:

import Tkinter as tk

class Application(tk.Frame):

    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()


def main():
    root = tk.Tk()
    root.geometry('200x150')
    app = Application(root)

    root.mainloop()

main()
like image 954
user1121487 Avatar asked Aug 11 '13 11:08

user1121487


1 Answers

While it is true that Tkinter uses old-style classes, this limitation can be overcome by additionally deriving the subclass Application from object (using Python multiple inheritance):

import Tkinter as tk

class Application(tk.Frame, object):

    def __init__(self, master):
        super(Application, self).__init__(master)
        self.grid()

def main():
    root = tk.Tk()
    root.geometry('200x150')
    app = Application(root)

    root.mainloop()

main()

This will work so long as the Tkinter class doesn't attempt any behaviour which requires being an old-style class to work (which I highly doubt it would). I tested the example above with Python 2.7.7 without any issues.

This work around was suggested here. This behaviour is also included by default in Python 3 (referenced in link).

like image 165
teletypist Avatar answered Sep 18 '22 23:09

teletypist