简体   繁体   English

每按一下按钮,Tkinter标签文本就会更改

[英]Tkinter label text changes with each button press

I have a basic Tkinter app with which I would like each Button press to update a Label with different values. 我有一个基本的Tkinter应用程序,我希望每次按下按钮时都可以使用不同的值更新标签。 I have created the Button & Label and am using a StringVar() to set the value of the Label. 我已经创建了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')

And then I have the following, currently not working function. 然后我有以下内容,目前无法正常工作。 My understanding is to implement some form of counter to track the Button presses, however I can not see a way of doing this after looking at other similar examples. 我的理解是实现某种形式的计数器来跟踪按钮按下,但是在查看其他类似示例之后,我看不到这样做的方法。

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)

Would anyone know of a solution to this? 有人知道解决方案吗? Thanks in advance. 提前致谢。

If the idea is to cycle through the list and change the label text every time the button is pressed, you could do something like this: 如果要在列表中循环浏览并在每次按下按钮时更改标签文本,则可以执行以下操作:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM