【发布时间】:2020-04-07 04:15:24
【问题描述】:
我发现了这个简单的 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...)
【问题讨论】:
-
如果您在
sleep之前添加root.update(),那么您会在按钮上看到此文本。 -
@furas 这是一个示例,但可能需要对 GUI 进行多次更新,同时希望 GUI 变得生动。
标签: python multithreading tkinter