[英]How to update tkinter label
所以我正在尝试制作某种基本的自动答题器,其排名会在一定数量的点击后更新,但每当我更新排名时,应该显示的 label 不会改变,我不知道如何进行 label 更新
from tkinter import *
count = 0
rank = "click the button to rank up!"
window = Tk()
if count == 1:
rank = "wow first click!"
def click():
global count
count += 1
counter = Label(window, text=count).grid(row = 0, column = 1)
clicker = Button(window, text="The Button", padx = 50, pady = 50, command = click).grid(row = 0, column = 0)
rankDisplay = Label(window, text = rank, padx = 100, pady = 25).grid(row = 1, column = 0)
window.mainloop()
第一次点击后,排名仍然显示为“点击按钮排名”而不是“哇第一次点击”,这就是问题所在
这是代码:
from tkinter import *
count = 0
window = Tk()
def changed(text):
rankDisplay.config(text=text)
rankDisplay.grid(row = 1, column = 0)
def click():
global count
count += 1
counter = Label(window, text=count).grid(row = 0, column = 1)
if count == 1:
changed("wow first click!")
return count
clicker = Button(window, text="The Button", padx = 50, pady = 50, command = click).grid(row = 0, column = 0)
rankDisplay = Label(window, text = "", padx = 100, pady = 25)
changed("click the button to rank up!")
window.mainloop()
当您单击按钮时,label 文本将“单击按钮排名”更新为“哇第一次点击”。因为 label 的文本是一个 StringVar(),如果我设置 stringvar,则 label 的文本将更新为 stringvar
我已经知道这个问题了。 要解决这个问题,您必须为您的 label 创建一个全局变量:
global l1
l1 = Label(...)
然后,要修改文本,您必须在函数中执行以下操作:
l1.config(text=str(count))
看到这里你应该使用名为rankDisplay
的 label 的update
方法
这是代码:
from tkinter import *
count = 0
window = Tk()
rank = StringVar()
rank.set("Click the button to rank up")
def click():
global count
count += 1
counter = Label(window, text=count).grid(row=0, column=1)
if count == 1:
rank.set("wow first click!")
rankDisplay.update()
clicker = Button(window, text="The Button", padx=50, pady=50, command=click).grid(row=0, column=0)
rankDisplay = Label(window, textvariable=rank, padx=100, pady=25)
rankDisplay.grid(row=1, column=0)
window.mainloop()
代码中的修改:您应该知道tkinter中StringVar
的概念才能使用update
方法..链接了解它https://www.pythontutorial.net/tkinter/tkinter-stringvar/#:~:text=The%20Tkinter %20StringVar%20helps%20you,Label%20or%20Entry%20more%20effectively.&text=The%20StringVar%20constructor%20accepts%20three,defaults%20to%20the%20root%20window 。
在rankDisplay
label 你必须使用textvariable
属性而不是text
只有这些是变化......
刚刚在第 16 行添加了rankDisplay.configure(...)
。
代码:
from tkinter import *
count = 0
rank = "click the button to rank up!"
window = Tk()
#if count == 1:
#rank = "wow first click!"
def click():
global count
count += 1
counter = Label(window, text=count)
counter.grid(row = 0, column = 1)
rankDisplay.configure(text="wow first click!")
clicker = Button(window, text="The Button", padx = 50, pady = 50, command = click).grid(row = 0, column = 0)
rankDisplay = Label(window, text = rank, padx = 100, pady = 25)
rankDisplay.grid(row = 1, column = 0)
window.mainloop()
Output:
点击后Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.