作者:重新生活好吗 | 来源:互联网 | 2024-10-19 11:13
我找到了这个简单的Hello World tkinter程序:
import tkinter as tk
class Application(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self,text="QUIT",fg="red",command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there,everyone!")
self.hi_there["text"] = "Hello World\n(click me again)"
root = tk.Tk()
app = Application(master=root)
app.mainloop()
如果我想让say_hi()
方法执行长时间运行的任务并同时偶尔更新GUI,该怎么办?
如果我尝试这样做:
def say_hi(self):
print("hi there,everyone!")
self.hi_there["text"] = "Hello World\n(wait...)"
sleep(2) # pretend to do something long-running
self.hi_there["text"] = "Hello World\n(click me again)"
然后,GUI在睡眠期间锁定,我再也看不到该按钮更改为:Hello World\n(wait...)
一个可能的解决方案是修改后的Application
类,该类在下面使用queue
和新方法poll()
作为Thread
希望执行的代码操作的消息泵运行。
from time import sleep
from queue import Queue
from threading import Thread
class Application(tk.Frame):
def __init__(self,master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
self.queue = Queue()
self.poll()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.start_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self,text="QUIT",fg="red",command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
def do_wait():
self.hi_there["text"] = "Hello World\n(wait...)"
def do_again():
self.hi_there["text"] = "Hello World\n(click me again)"
print("hi there,everyone!")
self.queue.put(do_wait)
sleep(2) # pretend to do something long-running
self.queue.put(do_again)
def start_hi(self):
thread = Thread(target = self.say_hi)
thread.start()
def poll(self):
if not self.queue.empty():
item = self.queue.get()
item()
self.master.after(100,self.poll)
如果使用此版本的课程,则会注意到hi_there Button
释放,并且按钮上的文本将按预期更改为wait...
。
腔体清空器:此代码还允许您创建许多Thread
实例,但是poll()
方法仅每100mS轮询一次