我的程序启动后加载插件,然后根据插件数量更新UI。那么怎样动态刷新UI?首先启动窗口后,再开始一个线程加载数据,最后更新窗口内容。
在窗口启动之前,开始线程加载数据:
import tkinter as tk
import _thread
root = tk.Tk()
root.title("hello tk")
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry("%dx%d+%d+%d" % (int(width / 2), int(height / 2), int(width / 4), int(height / 4)))
loadingLabel = tk.Label(root, text="loading")
loadingLabel.pack(fill='both', expand=True, anchor='center')
#启动线程
_thread.start_new_thread(loading, ())
root.mainloop()
在loading函数中加载数据以及更新UI
def loading():
# loading data
time.sleep(5)
if True:
# 清空UI
for widget in root.winfo_children():
widget.destroy()
# 显示成功
tk.Label(root, text="Data is loaded").pack(fill='both', expand=True, anchor='center')
else:
# 清空UI
for widget in root.winfo_children():
widget.destroy()
# 显示失败
tk.Label(root, text="Failed to load data").pack(fill='both', expand=True, anchor='center')
当线程结束后,窗口就会更新了。