我读过一些类似的问题,但我认为它们不能回答我的问题。
单击GUI中的“运行”按钮后,我有一个基本代码可以计数到10:
from tkinter import *
from time import sleep
def count_to_10():
for i in range(1,11):
sleep(0.5)
print(i)
counter_label.after(0, counter_label.config(text=i))
return
def GUI():
root = Tk()
run_button = Button(root, text="run", command=count_to_10)
run_button.pack()
global counter_label
counter_label = Label(root, text="counter")
counter_label.pack()
root.mainloop()
GUI()
我希望函数counter_label
每次迭代后,文本从1变为10 count_to_10
。当函数返回时,标签会更改,而不是在运行时。
控制台输出:
1
2
3
4
5
6
7
8
9
10
标签更改:
同样的结果也适用于诸如此类的其他小部件scrolledtext, Text,
。
函数运行时如何更改标签(或任何与文本相关的小部件)?
谢谢你的帮助!
PS:有点像在GUI上有控制台输出。
您不需要使用该x.after()
方法。只需使用config
orconfigure
方法。像这样:counter_label.configure(text=i)
然后您应该让root用以下行来更新主窗口:root.update()
(root应该是全局的或作为参数传递)。
完整的代码:
from tkinter import *
from time import sleep
def count_to_10():
for i in range(1, 11):
sleep(0.5)
print(i)
counter_label.configure(text=i) # Update the text in "Label" widget.
root.update() # Let root update the main window.
def GUI():
global root
root = Tk()
run_button = Button(root, text="run", command=count_to_10)
run_button.pack()
global counter_label
counter_label = Label(root, text="counter")
counter_label.pack()
root.mainloop()
GUI()
GUI:
控制台输出:
>>> python3 test.py
1
2
3
4
5
6
7
8
9
10
注意:
您的Label仅更改了一次(计数器为10时),因为root
它无法更新,并且在count_to_10
函数返回后(for
循环之后)更新了它,当然最后一个数字是10
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句