2017-06-20 44 views
0

我試圖創建一個子類,tkinter.Canvas的Square,在點擊左鍵時會出現一行。我已經得到了部分的工作,但是當我嘗試,並通過寬度和高度爲我的Square類,我得到的錯誤:基類的Python傳遞參數

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() 

回答

3

該錯誤的關鍵詞是「位置」。您將參數傳遞爲應作爲關鍵字參數傳遞的位置。改變這一行:

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

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

作爲一個側面說明,對於Canvas.__init__調用簽名是:

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

所以這三個可能的位置參數是self(提供自動時調用綁定方法),mastercnf。其中mastercnf是可選的。

+0

謝謝,我明白。 – Qiri