简体   繁体   English

Python tkinter 正在加载

[英]Python tkinter loading in progress

I would like to know how to display the text "loading in progress" while the final text is loading after pressing the execute button?我想知道如何在按下执行按钮后加载最终文本时显示文本“正在加载”?

import time
import random
import tkinter as tk


def load():
    my_label.config(text="Loading in progress...")  #how to display it?
    my_time = random.randint(1,10)
    time.sleep(my_time)
    my_label.config(text="Loaded!!!")

root = tk.Tk()
root.geometry('300x300')

my_button = tk.Button(root, text='Load', width=20, command=load)
my_button.pack(pady=20)

my_label = tk.Label(root, text='')
my_label.pack(pady=20)


root.mainloop()

Thank you for your answers谢谢您的回答

Use.after instead of sleep in tkinter to avoid blocking the main loop.在 tkinter 中使用 .after 代替 sleep 以避免阻塞主循环。

import time
import random
import tkinter as tk
from functools import partial

my_time = None

def load(my_time):
    if my_time is None:
        my_time = random.randint(2, 10)
    my_label.config(text=f"Loading in progress...{my_time}")
    my_time -=1
    timer = root.after(1000, load, my_time)
    if not my_time:
        root.after_cancel(timer)
        my_label.config(text="Loaded!!!")


root = tk.Tk()
root.geometry('300x300')

my_button = tk.Button(root, text='Load', width=20, command=partial(load, my_time))
my_button.pack(pady=20)

my_label = tk.Label(root, text='')
my_label.pack(pady=20)

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM