Python 传递基数 class 的参数

Python pass arguments of base class

我正在尝试创建一个子类,Square of tkinter.Canvas,单击鼠标左键会在其上显示一条线。我已经让那部分工作了,但是当我尝试将宽度和高度传递到我的 Square Class 时,我收到错误:

Traceback (most recent call last):
  File "tictac.py", line 16, in <module>
    square = Square(master=root, width=200, height=200)
  File "tictac.py", line 5, in __init__
    super().__init__(master, width, height)
TypeError: __init__() takes from 1 to 3 positional arguments but 4 were given

我之前 运行 遇到过类似的问题,其中 "self" 作为参数传入。这就是这里发生的事情吗?有人可以向我解释一下这是如何工作的吗?

代码如下,如果我删除所有对宽度和高度的引用,它会按我想要的方式工作,显然不是我想要的宽度和高度。

import tkinter as tk

class Square(tk.Canvas):
        def __init__(self, master=None, width=None, height=None):
                super().__init__(master, width, height)
                self.pack()
                self.bind("<Button-1>", self.tic)


        def tic(self, event):
                """"This will draw a nought or cross on the selected Square."""
                self.create_line(0, 0, 200, 100)


root = tk.Tk()
square = Square(master=root, width=200, height=200)
root.mainloop()

该错误中的关键字是 "positional"。您正在传递应作为关键字参数传递的位置参数。更改此行:

super().__init__(master, width, height)

super().__init__(master, width=width, height=height)

作为旁注,Canvas.__init__ 的呼叫签名是:

__init__(self, master=None, cnf={}, **kw)

因此三个可能的位置参数是self(调用绑定方法时自动提供)、mastercnf。其中 mastercnf 是可选的。