[英]How to update labels in tkinter dynamically?
我創建了此代碼,該代碼每秒更新一次標簽以指示正在加載某些內容(運行代碼以了解我的意思)。 我在tkinter中使用線程模塊,但我覺得必須有一種更有效的方法來執行此操作。
這是我的代碼:
from tkinter import *
from time import sleep
import threading
root = Tk()
new_var = StringVar()
new_var.set('Loading')
def change_text():
array = [".", "..", "...", ""]
while True:
for num in range(4):
sleep(1)
new_var.set(f"Loading{array[num]}")
root.update_idletasks()
l = Label(root, textvariable = new_var)
l.pack()
Loading_animation = threading.Thread(target=change_text)
Loading_animation.start()
root.mainloop()
另外,如果沒有更好的方法來執行此操作,那么如何防止我在關閉根窗口時始終收到的錯誤?
謝謝!
這是一個不涉及線程的簡單方法。
保留一個計數器,然后每秒調用該函數。 在函數中,只需將計數器中的每個項目的文本設置為索引即可。
更新:在評論中回答您的問題。
這不會陷入使我們無法到達mainloop()
某個循環中,因為此代碼僅添加了一個命令,該命令以1秒的固定間隔在事件列表上運行。 實際發生的事情是after()
方法將添加一個新的,甚至運行不超過1秒(1000毫秒)。 因為Tkinter是事件驅動的,所以即使在每個mainloop()
周期之后,Tkinter也會處理列表中的每個mainloop()
。
import tkinter as tk
root = tk.Tk()
counter = 0
def change_text():
global counter
my_list = [".", "..", "...", ""]
if counter != 3:
l.config(text="Loading{}".format(my_list[counter]))
counter += 1
root.after(1000, change_text)
else:
l.config(text="Loading{}".format(my_list[counter]))
counter = 0
root.after(1000, change_text)
l = tk.Label(root, text = "")
l.pack()
change_text()
root.mainloop()
這是與@ Mike-SMT相同的答案,但是使用循環功能使其更加整潔。
import tkinter as tk
from itertools import cycle
root = tk.Tk()
my_list = cycle([".", "..", "...", ""])
def change_text():
l.config(text="Loading{}".format(next(my_list)))
root.after(1000, change_text)
l = tk.Label(root)
l.pack()
change_text()
root.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.