[英]Tkinter label text changes with each button press
我有一个基本的Tkinter应用程序,我希望每次按下按钮时都可以使用不同的值更新标签。 我已经创建了Button&Label,并且正在使用StringVar()
设置Label的值。
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)
有人知道解决方案吗? 提前致谢。
如果要在列表中循环浏览并在每次按下按钮时更改标签文本,则可以执行以下操作:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.