TypeError: __init__() takes exactly 2 arguments (3 given)

TypeError: __init__() takes exactly 2 arguments (3 given)

我不知道为什么错误显示它有3个参数。有人可以帮忙吗?

Traceback:
  line 23, in __init__
    frame = F(self, container)
TypeError: __init__() takes exactly 2 arguments (3 given)

代码:

class CGPACalculator(Tkinter.Tk):
    def __init__(self, *args, **kwargs):
        Tkinter.Tk.__init__(self, *args, **kwargs)
        container = Tkinter.Frame(self)

        container.pack(side="top", fill="both", expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (Page1, Page2):
            frame = F(self, container)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(Page1)

简单地说,当你调用 F(self, container) 构造函数时,你将 两个 参数传递给构造函数,但 Python 还包括新创建的object 因为它是第一个参数,这就是为什么它告诉你 three arguments were given.

看这个例子:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

foobar = Foo('bar')
print(foobar.bar)

这将创建一个类型为 Foo 的新对象,并在新对象上打印 bar 的值。这是输出:

bar

注意 __init__ 方法是如何用 两个 参数声明的,但是当用 Foo('bar') 创建一个新对象时,我们只用 一个个参数。

构造函数需要两个参数,但第一个是要创建的对象的实例。传递的其余参数将是调用构造函数时传递的任何参数。

所以在你的例子中,Page1Page2 classes 有一个 __init__ 方法和 两个 参数,这意味着您需要使用 one 参数调用它,因为第一个自动成为相应 class.

的新实例

@fhdrsdg 指出了所有添加的 class 应该具有相同定义的答案:

class Page1(Tkinter.Frame):
    def __init__(self, parent, controller):
        Tkinter.Frame.__init__(self, parent)


class Page2(Tkinter.Frame):
    def __init__(self, parent, controller):
        Tkinter.Frame.__init__(self, parent)

等等...

您可以看到所有页面 class 具有相同的升序 (self, parent, controller)。不仅如此,每页第3行的(self,parent)顺序相同,以便程序运行。

否则不会运行或给出参数错误