python-3.x - 如何在 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()
解决方案
您可以在代码中使用 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)
推荐阅读
- javascript - 有没有办法从数组中取出对象并放入新数组中?
- javascript - 如何根据所选下拉列表的值隐藏和显示 div -JQuery 和 Javascript
- highcharts - highcharts中的数据标签
- angularjs - 错误 TS1128:.map() 运算符需要声明或语句
- javascript - 如何配置 TypeScript 以针对不正确的导入语句引发错误/警告?
- javascript - How to fill in missing months in an array using javascript
- java - 如何在清单中链接外部 Spring Boot JAR (NoClassDefFoundError)
- spring - 在运行时更改 thymeleaf 角色
- node.js - 获取托管 FireBase 功能或 Google APP Engine 的固定 IP
- vba - 在 Mac 中替换为 ChrW() - 在 Windows 上正常工作