2016-01-20 52 views
3

我試圖用configure方法更改我的應用程序的標籤。標籤是在for循環中動態生成的。這裏是代碼的一部分:Tkinter:動態生成標籤的配置方法

# create a list of reference for labels equal to zero 
self.lbl_areas = [] 
for i in range(0, len(self.samples)): # number of labels 
    lbl=tk.IntVar() 
    lbl.set(0) 
    self.lbl_areas.append(tk.Label(self.win,textvariable=lbl)) 

# Place labels on the application using grid    
for i,v in enumerate(self.lbl_areas): 
    v.grid(row=2+i,column=1,sticky=tk.W) 

# Try to change the value 
for i in range(0, len(self.samples)): 
    self.lbl_areas[i].configure(textvariable=lbl_val[i]) # other values 

顯示默認的零值,但配置方法似乎不起作用。我做錯了什麼?

回答

2

在創建標籤後有兩種方法更新標籤。首先是使用文本變量,更新變量並且標籤自動獲取變化。第二個是你不使用文本變量的地方,而是改變標籤的文本。你正試圖混合兩者。

在我看來,最好的辦法是不是使用textvariable。這是一個額外的對象,你需要跟蹤哪個沒有提供額外的好處(在這種情況下,無論如何)。

在你的情況我會寫這樣的代碼:如果你想使用textvariable屬性

for i in range(0, len(self.samples)): # number of labels 
    self.lbl_areas.append(tk.Label(self.win,text="0")) 
... 
for i in range(0, len(self.samples)): 
    self.lbl_areas[i].configure(text=lbl_val[i]) 

,那麼你就需要一個參考保存到變量,以便以後可以將其設置:

for i in range(0, len(self.samples)): # number of labels 
    lbl=tk.IntVar() 
    lbl.set(0) 
    self.lbl_areas.append(tk.Label(self.win,textvariable=lbl)) 
    self.lbl_vars.append(lbl) 
... 

for i in range(0, len(self.samples)): 
    self.lbl_vars[i].set(lbl_val[i]) 

注意,在這兩種情況下,你必須調用一個函數(configureset)更改值。您可以在小部件(widget.configure(...))或變量(var.set(...))上調用它。除非你正在利用tkinter變量的特殊屬性 - 比如在兩個或多個小部件之間共享變量,或者使用可變跟蹤 - 否則,如果沒有textvariable,代碼將變得更簡單。

+0

工作正常。非常感謝你!我將使用第二個選項:更改標籤文本。 – diegus