Python 2.7 super() error [duplicate]

杀马特。学长 韩版系。学妹 提交于 2019-11-27 06:21:40

问题


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

super(Application, self)._init_(master) TypeError: 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()

回答1:


Tkinter uses old-style classes. super() can only be used with new-style classes.




回答2:


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).



来源:https://stackoverflow.com/questions/18171328/python-2-7-super-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!