2016-06-18 45 views
3

我想在Python中創建一個簡單的計時器和我旨在建立使用類的用戶界面。我想用這些類來初始化用戶界面。然後在主體的正文中,我想使用.grid和.configure方法添加屬性。但是當我嘗試這樣做時,錯誤:'statInter'對象沒有屬性'tk'出現。錯誤的解釋 - 「statInter」對象有沒有屬性「TK」

我在編程初學者,但如果我理解正確的錯誤它的結果,因爲.grid和其他按鈕的方法不由我statInter繼承(即靜態接口)類。它是否正確?我該如何解決這個錯誤?我修改了繼承Button類甚至Tk類的屬性,但在後面的情況下,我得到一個無限循環,即超過最大遞歸深度。

感謝您的幫助

#This is a simple timer version 

from tkinter import * 

window = Tk() 
window.title('Tea timer') 
window.minsize(300,100) 
window.resizable(0,0) 

class statInter(Button,Entry): 

    def __init__(self, posx, posy): 
     self.posx = posx # So the variables inside the class are defined broadly 
     self.posy = posy 

    def button(self): 
     Button(window).grid(row=self.posx, column=self.posy) 

    def field(self): 
     Entry(window, width=5) 

sth = statInter(1,2) 
sth.grid(row=1, column = 2) 

window.mainloop() 

回答

4

的問題是你的派生類StatInterCamelCasingPEP 8 - Style Guide for Python Code建議的類名)不初始化它的基類,通常隱含在Python中發生(因爲它在說,C++一樣)。

爲了在StatInter.__init__()方法中做到這一點,您將需要知道將包含它的parent小部件(除頂層窗口以外的所有小部件都包含在層次結構中) - 因此需要額外的參數傳遞給派生類的構造函數,以便將其傳遞給每個基類構造函數。

您還沒有很快就遇到了另一個問題還沒有,但有可能會。爲了避免它,你也將有明確地傳遞self明確調用button()field()基類的方法時。

from tkinter import * 

window = Tk() 
window.title('Tea timer') 
window.minsize(300,100) 
window.resizable(0,0) 

class StatInter(Button, Entry): 

    def __init__(self, parent, posx, posy): # Added parent argument 
     Button.__init__(self, parent) # Explicit call to base class 
     Entry.__init__(self, parent) # Explicit call to base class 
     self.posx = posx # So the variables inside the class are defined broadly 
     self.posy = posy 

    def button(self): 
     Button.grid(self, row=self.posx, column=self.posy) # Add self 

    def field(self): 
     Entry.config(self, width=5) # Add self 

sth = StatInter(window, 1, 2) # Add parent argument to call 
sth.grid(row=1, column=2) 

window.mainloop() 
+0

這是一個很好的答案,但我懷疑OP是_either_想從'Button'和'Entry',繼承_or_使用的組合物,以創建一個'Button'和'Entry',但不能同時使用。 –

+0

@Bryan:謝謝。當然,你說的是「存在」與「存在」的問題。我試圖回答得很好,以解決眼前的問題,所以OP可以繼續他們的開發 - 並指出了在Python中進行多重繼承時可能出現的一些潛在缺陷,這也許正是我們想要完成的。 – martineau

1

你得到這個錯誤的原因是因爲你永遠不調用任何構造函數的從你的(無論是ButtonEntry)繼承的類。

如果您改變__init__是:

def __init__(self, posx, posy): 
    Button.__init__(self) 
    self.posx = posx # So the variables inside the class are defined broadly 
    self.posy = posy 

然後,你不會得到你以前有錯誤,和一個小窗口彈出。在新的__init__中,我們明確調用了Button的構造函數。

不像Java和其他一些語言中,super構造不按默認值調用。我假設從其他tkinter類繼承的每個類必須有一個tk字段。通過調用你選擇的父構造函數,這個字段將被創建。如果你不調用父類的構造,雖然,那麼這將不會是一個既定的場,你會得到你所描述的錯誤(「statInter」對象有沒有屬性「TK」)。

HTH!

相關問題