我如何在 tkinter 时使用 Work

How can I use the Work while tkinter

函数运行 tkinter 冻结。 我想使用 Tkinter window 运行 那个 process.While 运行 进度条 我想使用 tkinter window.but 我不能 因为它冻结了 tkinter。我如何在 time.sleep(10) 或其他功能工作时使用 root window

import tkinter.ttk as ttk
import tkinter as tk
import time

progress = 0


def loading(window=None):
    mpb = ttk.Progressbar(window, orient="horizontal", length=200, mode="determinate")
    mpb.place(y=0, x=0)
    mpb["maximum"] = 100
    mpb["value"] = progress
    print(progress)


def incrase():
    global progress
    print(progress)
    progress += 1
    time.sleep(10)  # for example, a function works here and tkinter freezes
    loading()       # i don't want tkinter freezes


root = tk.Tk()
loading(root)
ttk.Button(root, text='increase', command=incrase).place(x=0, y=25, width=90)

root.mainloop()

感谢解答

您应该使用 after() 来安排 loading() 函数在一段时间后调用。

计划

以下是如何在您的程序中使用它:

import tkinter.ttk as ttk
import tkinter as tk
import time

progress = 0


def loading(window):
    mpb = ttk.Progressbar(window, orient="horizontal", length=200, mode="determinate")
    mpb.place(y=0, x=0)
    mpb["maximum"] = 100
    mpb["value"] = progress
    print(progress)


def incrase():
    global root
    global progress
    print(progress)
    progress += 1
    root.after(10, loading(root))  # schedule loading() 



root = tk.Tk()
loading(root)
ttk.Button(root, text='increase', command=incrase).place(x=0, y=25, width=90)

root.mainloop()

演示

上面运行程序的截图: