[英]How to properly update tkinter label element
我正在创建一个有两个值的秒表。 它从值 A 开始倒数到 0,然后更改为值 B,倒数到 0,然后回到值 A,倒数到 0 等等,直到我关闭程序(我可能会在某些地方添加一个暂停按钮点),总的来说,它工作得很好。 但是,当它使用新文本更新 label 时,它似乎只是在制作一个新文本项并将其作为一个图层放在先前的顶部。 然后我可以看到当我 go 从一个两位数到一位数,并且句子被缩短时,仍然可以看到旧句子中没有覆盖的部分。 所以我希望我只是错过了一些非常简单的东西。 我认为newWindow.update()
会更新 window 但它似乎没有这样做。 下面是我处理逻辑的代码片段。
def countdown(timer_count,count_type):
counter = timer_count
count_type = count_type
while counter >= 0:
timer = tk.Label(newWindow, text=f"{count_type} for: {counter}")
timer.config(font=("TkDefaultFont",30))
timer.grid(row=0,column=2)
newWindow.update()
time.sleep(1)
counter -= 1
print(counter)
if count_type == "work":
count_type = "rest"
elif count_type == "rest":
count_type = "work"
return count_type
def interval():
counter_type = "work"
while True:
if counter_type == "work":
counter_type = countdown(int(exer_var.get()),counter_type)
elif counter_type == "rest":
counter_type = countdown(int(rest_var.get()),counter_type)
每次通过 while 循环创建一个新的Label
小部件,而不是更改 while 循环内的文本。 这就是为什么它将一个小部件层叠在另一个之上的原因,因此您需要创建小部件,然后运行 while 循环,并在循环内的timer.config
中设置要更改的文本。 您还应该在原始tk.Label
中声明字体,无需更改每次循环。 对于“some_starting value”,它可能是text = counter
timer = tk.Label(newWindow, font=("TkDefaultFont",30), text="some_starting_value")
while counter >= 0:
timer.config(text=f"{count_type} for: {counter}")
timer.grid(row=0,column=2)
从您的代码中很难说出发生这种情况的位置,但通常是这样做的:
timer = tk.Label(newWindow,font=("TkDefaultFont",30)) # Adding the font here itself
config
更改其值:def countdown(timer_count,count_type):
counter = timer_count
count_type = count_type
while counter >= 0:
timer.config(text=f"{count_type} for: {counter}") # Update the options for the created label.
timer.grid(row=0,column=2)
因此,现在每次运行函数/循环时,都不会创建和覆盖新标签,而是将配置现有的 label。
附带说明一下,使用time.sleep()
和while
循环并不是最好的做法,即使使用update()
它仍然会对 GUI 造成某种干扰。 相反,重新安排您的代码以使用after(ms,func)
方法,这不会冻结 GUI。 如果您以后遇到任何麻烦,您可以提出一个新问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.