Tkinter标签文本随每个按钮按下更改

问题描述:

我有一个基本的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

如果这个想法是循环列表,每次按下按钮时更改标签的文本,你可以做这样的事情:

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