Tkinter标签文本随每个按钮的按下而改变

2024-10-03 00:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基本的Tkinter应用程序,我想每按一个按钮,以更新不同的值标签。我已经创建了按钮和标签,并使用StringVar()来设置标签的值。你知道吗

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)

有人知道解决这个问题的办法吗?提前谢谢。你知道吗


Tags: theself应用程序tkinterlabupdate标签按钮
1条回答
网友
1楼 · 发布于 2024-10-03 00:27:34

如果要在列表中循环并在每次按下按钮时更改标签文本,可以执行以下操作:

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()

相关问题 更多 >