【问题标题】:TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its basesTypeError:元类冲突:派生类的元类必须是其所有基类的元类的(非严格)子类
【发布时间】:2017-10-04 18:42:37
【问题描述】:

尝试使用类创建 GUI,但我一直遇到此错误的问题。我不确定这意味着什么,因为据我所知,我只有一门课,我的错误是:

Traceback (most recent call last):
File "C:/Users/Blaine/Desktop/Computing Project.py", line 5, in <module>
class SneakerSeeker(tk,Frame):
TypeError: metaclass conflict: the metaclass of a derived class must be a 
(non-strict) subclass of the metaclasses of all its bases

我的代码是:

from tkinter import * 
import tkinter as tk
import tkinter.messagebox as tm

class Number1(tk,Frame):
    def __init__(self, master):
        super(Number1, self).__init__()
        self.master = master
        self.frame = tk.Frame(self.master)
        self.TopTitle = Label("Number1", font = ('Calibri ', 16))
        self.TopTitle.pack()


def main():
    root = tk.Tk()
    root.title("Number 1")
    app = Number1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python python-3.x class user-interface tkinter


    【解决方案1】:

    我想评论你,但有很多话要说:

    • 首先,去掉 from tkinter import * 并改写 import tkinter as tk(正如 Bryan 在这里写过很多次)。除此之外,在同一个应用程序中编码from tkinter import *import tkinter as tk 的目的是什么?当你这样做时,你所有的小部件类必须以tktk.Label(...)tk.Frame(...)...)为前缀

    • class Number1(tk,Frame) 中你应该写tk.Frame(或者如果你保持你的导入原样,就写Frame

    • 您在super(Number1, self).__init__() 中不必要地使用了super()。请在此处阅读 Bryan 的答案:Best way to structure a tkinter application,并将该行替换为:tk.Frame.__init__(self, master)(以后请考虑Python's Super is nifty, but you can't use it

    • 关于这一行:self.TopTitle = Label("Number1", font = ('Calibri ', 16)):传递给tk.Label()(以及您将创建的任何其他小部件)的第一个选项是父小部件:在您的情况下,self.master

      李>
    • 我发现与 self.TopTitle 相关的 2 行没有用,我不明白你想用它们实现什么(此外,你不应该那样命名标签;如果你愿意,请尊重 PEP 8加入 Python 教派)

    【讨论】:

    • 嗯?使用super 没有任何问题。事实上,它比tk.Frame.__init__ 更好,因为您不必硬编码父类的名称。
    • 也许值得一提的是,错误信息与第二段有关,可能是错字tk,Frame 而不是tk.Frame
    猜你喜欢
    • 1970-01-01
    • 2021-11-23
    • 2021-06-18
    • 1970-01-01
    • 2017-12-29
    • 2018-09-09
    • 2016-09-20
    • 1970-01-01
    • 2018-06-21
    相关资源
    最近更新 更多