[Tkinter 101] 03 清空窗口控件,更新窗口控件

我的程序启动后加载插件,然后根据插件数量更新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')

当线程结束后,窗口就会更新了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值