我正在尝试创建一个子类,tkinter的平方。画布,单击鼠标左键时将显示一条线。我已经让该部分正常工作,但是当我尝试将宽度和高度传递到我的方形类中时,出现错误:
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
我以前遇到过类似的问题,其中"自我"被作为论据传递。这是这里发生的事情吗?有人可以向我解释一下这是如何工作的吗?
代码如下,如果我删除对宽度和高度的所有引用,它就可以按照我想要的方式工作,显然除了我想要的宽度和高度之外。
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()
该错误的关键词是"位置"。您正在将参数作为位置传递,应作为关键字参数传递。更改此行:
super().__init__(master, width, height)
自
super().__init__(master, width=width, height=height)
作为旁注,Canvas.__init__
的呼叫签名是:
__init__(self, master=None, cnf={}, **kw)
因此,三种可能的位置参数是self
(调用绑定方法时自动提供(、master
和cnf
。其中master
和cnf
是可选的。