2016-08-12 92 views
0

當我嘗試運行我的代碼,我得到這個錯誤:Tkinter的Python函數需要1個參數,給出2

File "./countdown.py", line 36, in <module> 
    app = Application(root) 
File "./countdown.py", line 16, in __init__ 
    self.create_buttons(self) 
TypeError: create_buttons() takes exactly 1 argument (2 given) 

這裏是我的代碼:

import Tkinter as tk 

class Application(tk.Frame): 
    """Countdown app - simple timer""" 

    def __init__(self, master): 
    """initialize frame""" 
    tk.Frame.__init__(self, master) 
    #super(Application, self).__init__(master) 
    self.grid() 
    self.create_buttons(self) 

    def create_buttons(self): 
    self.startBttn = Button(app, text = "Start") 
    self.startBttn.grid() 
    self.stopBttn = Button(app, text = "Stop") 
    self.stopBttn.grid() 
    self.resetBttn = Button(app, text = "Reset") 
    self.resetBttn.grid() 


### Main Code ### 

# create the root window using Tk - an object of tkinter class 
root = tk.Tk() 

# modify the prog. window (set size, title, etc.) 
root.title("Countdown") 
root.geometry("200x100") 
#instantiate Application 
app = Application(root) 

我一直在尋找這個答案有一段時間,但是還沒有能夠將其他人的解決方案應用於我的代碼 - 任何想法?如果我刪除tk。在類之前應用程序聲明我得到一個錯誤,說幀未找到。如果我使用super(Application,self).__ init __(master)而不是上面的行,我得到一個類型錯誤,必須是類而不是類對象。

回答

3

調用綁定方法時,不要明確地傳遞self。這樣稱呼它:

self.create_buttons() 

通過調用方法與self.create_buttons(self)函數接收參數:調用綁定方法(Python的自動執行此操作)時所傳遞的隱含self,並明確self你傳入方法調用。


也有一些其他問題create_buttons()您可以使用此代碼修復:

def create_buttons(self): 
    self.startBttn = tk.Button(self, text = "Start") 
    self.startBttn.grid() 
    self.stopBttn = tk.Button(self, text = "Stop") 
    self.stopBttn.grid() 
    self.resetBttn = tk.Button(self, text = "Reset") 
    self.resetBttn.grid() 

的變化是,你需要使用tk.Button引用Button類,並通過selftk.Button這是對父幀的引用。這裏selfApplication實例,它是tk.Frame的子類 - 因此self是一個幀。

最後,您需要添加一個調用mainloop()

#instantiate Application 
app = Application(root) 
root.mainloop() 

關於與super的問題,Tkinter的類是「舊式」型的,並且不支持super()。因此,您必須使用tk.Frame.__init__(self, master)來調用基類。

有一種解決方法是使用多重繼承,包括object作爲基類。如果聲明Application爲:

class Application(tk.Frame, object): 
    def __init__(self, master): 
     """initialize frame""" 
     super(Application, self).__init__(master) 

那麼你可以使用super(),但它是辛苦錢。

+0

而'app.mainloop()'用於要繪製的窗口和要處理的事件。 –

+0

@AbhishekBalajiR:啊,是的,這也是必需的,謝謝。 – mhawke

+0

這工作 - 謝謝你的解釋 – potatopie

相關問題