簡體   English   中英

每按一下按鈕,Tkinter標簽文本就會更改

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM