首页 > 解决方案 > 如何在 TkInter 中实现“处理请求”消息

问题描述

我正在尝试实现一个弹出窗口,它应该显示在主窗口上,同时在后台进行操作。从下面的代码中按下按钮会导致 GUI 冻结 10 秒而不显示任何消息并最终使按钮变为绿色。冻结是正常的,但我希望在 10 秒内显示弹出窗口。任何帮助,将不胜感激!提前致谢!

import tkinter as tk
import time

class GUI(tk.Tk):
    def __init__(self):
        super().__init__()

        self.button1 = tk.Button(text="Start", command=self.make_green)
        self.button1.pack()


    def popup(self):
        tl = tk.Toplevel(self)
        tl.transient()
        tk.Label(tl, text="Painting green").pack()
        tl.grab_set()
        return tl

    def make_green(self):
        wait_popup = self.popup()
        time.sleep(10)
        self.button1.config(bg="green")
        wait_popup.destroy()

a = GUI()
a.mainloop()

标签: python-3.xtkinter

解决方案


您可以在代码中使用 self.update() 来显示弹出窗口。

import tkinter as tk
import time

class GUI(tk.Tk):
    def __init__(self):
        super().__init__()

        self.button1 = tk.Button(text="Start", command=self.make_green)
        self.button1.pack()


    def popup(self):
        tl = tk.Toplevel(self)
        tl.transient()
        tk.Label(tl, text="Painting green").pack()
        self.update()
        tl.grab_set()
        return tl

    def make_green(self):
        wait_popup = self.popup()
        time.sleep(10)
        self.button1.config(bg="green")
        wait_popup.destroy()

a = GUI()
a.mainloop()

或者你可以使用线程。

首先从 threading 导入 Thread。

from threading import Thread

然后做一个新方法

def thread_it(self):
    return Thread(target=self.make_green, daemon=True).start()

并更新按钮的命令

self.button1 = tk.Button(text="Start", command=self.thread_it)

推荐阅读