如何在不冻结 GUI 的情况下 运行 来自 TKinter 的方法?

How do I run a method from TKinter without having the GUI freeze up?

假设我有一个在 TKinter 中按下按钮时 运行 的方法。此方法打开一个外部应用程序(即 Excel、Powerpoint 等。我的程序打开的应用程序需要更长的时间才能打开,这就是我需要加载对话框的原因)

我正在尝试打开一个小的自定义 tk.toplevel 加载对话框,它将在外部应用程序加载时显示和 takefocus

但是,每当 TKinter 运行 打开应用程序的方法时,整个过程就会冻结,我的加载对话框只有在应用程序最终打开后才可见。

有没有办法在后台打开应用程序的同时显示我的加载对话框?

不是同时。而是先打开对话框,然后调用打开其他应用程序的方法。您将必须通过在冻结 GUI 的方法之前调用 update_idletasks 来强制绘制对话框,否则直到程序空闲时才会绘制对话框并且为时已晚。

在此示例中,我使用 time.sleep 来模拟一个使应用程序保持忙碌且 GUI 冻结的任务。

import time
import tkinter as tk


class App():
    def __init__(self):
        self._root = tk.Tk()
        b = tk.Button(self._root, text='Click me', command=self.onclick)
        b.pack()

    def run(self):
        self._root.mainloop()

    def onclick(self):
        dialog = tk.Toplevel(self._root)
        tk.Label(dialog, text='Loading...').pack()
        dialog.update_idletasks()
        self.this_takes_a_long_time()
        dialog.destroy()

    def this_takes_a_long_time(self):
        time.sleep(5)


App().run()