2016-04-21 109 views
0

我有一個基本的Tkinter應用程序,我希望每個按鈕按下更新具有不同值的標籤。我創建了Button &標籤,並使用StringVar()來設置標籤的值。Tkinter標籤文本隨每個按鈕按下更改

button3 = tk.Button(self, text="Test", command=self.update_label) 
button3.pack() 

lab = tk.Label(self, textvariable=self.v) 
lab.pack() 

self.v = StringVar() 
self.v.set('hello') 

然後我有以下,目前不工作的功能。我的理解是實現某種形式的跟蹤按鈕的計數器,但是在查看其他類似示例後,我無法看到這樣做的方式。

def update_label(self): 
    click_counter = 0 # I have only included as I believe this is the way to go? 
    texts = ['the first', 'the second', 'the third'] 
    for t in texts: 
     self.v.set(t) 

有人會知道這個解決方案嗎?提前致謝。

+0

假設你使用類,使用'self.click_counter ' –

+0

我正在使用類,我應該把自己放在那個click_counter - 我的錯誤 – eggman

回答

0

如果這個想法是循環列表,每次按下按鈕時更改標籤的文本,你可以做這樣的事情:

import sys 
if sys.version_info < (3, 0): 
    from Tkinter import * 
else: 
    from tkinter import * 

class btn_demo: 
    def __init__(self): 
     self.click_count = 0 
     self.window = Tk() 
     self.btn_txt = 'Change label!' 
     self.btn = Button(self.window, text=self.btn_txt, command=self.update_label) 
     self.btn.pack() 
     self.lab = Label(self.window, text="") 
     self.lab.pack() 
     mainloop() 

    def update_label(self): 
     texts = ['the first', 'the second', 'the third'] 
     self.click_count = (self.click_count + 1) % len(texts) 
     self.lab["text"] = texts[self.click_count] 


demo = btn_demo() 
+0

完美 - 非常感謝! – eggman

+0

@ user3125923不客氣 – jDo

相關問題