Python 2.7 super()错误

use*_*487 4 python tkinter super

尝试使用super()创建Tkinter窗口.我收到此错误:

super(Application,self)._ init _(master)TypeError:必须是type,而不是classobj

码:

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

tel*_*ist 9

虽然Tkinter使用旧式类是正确的,但是通过另外Applicationobject(使用Python多重继承)派生子类可以克服这种限制:

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

只要Tkinter类没有尝试任何需要成为旧式类的行为(我非常怀疑它会这样),这将起作用.我用Python 2.7.7测试了上面的例子,没有任何问题.

这里提出这个工作.默认情况下,Python 3中也包含此行为(在链接中引用).


Ign*_*ams 3

Tkinter使用旧式类。只能与新式类super()一起使用。