按下按钮时 Tkinter GUI 卡在任务结束前
Tkinter GUI stuck till end of the task when pressing a button
当我按下 "start program" 按钮时,它会启动一个 5 秒的任务并阻止 GUI。
据我所知,我需要使用线程,这样每个按钮都可以独立于 GUI 工作。
我已经被困了将近一个月了,谁能告诉我如何执行 def start_Button(self)
: function using threading?
from tkinter import *
import time
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.var = IntVar()
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text="Exit", command=self.client_exit)
startButton = Button(self, text="Start Program", command=self.start_Button)
quitButton.grid(row=0,column=0)
startButton.grid(row=0, column=2)
def client_exit(self):
exit()
def start_Button(self):
print('Program is starting')
for i in range (5):
print(i)
time.sleep(1)
root = Tk()
root.geometry("200x50")
app = Window(root)
root.title("My Program")
root.mainloop()
在您第一次进入线程之前,有很多重要的问题要问,但总的来说最重要的问题是 "how do I want to communicate between my threads?"在您的最小示例中,您不需要任何沟通所有,但是在您的真实代码中 start_Button
可能正在做一些工作并将数据返回给 GUI。如果是这样的话,你还有更多的工作要做。如果是这种情况,请在评论中加以澄清。
对于最小的例子,其实很简单。
class Window(tkinter.Frame):
# the rest of your GUI class as written, but change...
def start_Button(self):
def f():
# this is the actual function to run
print('Program is starting')
for i in range (5):
print(i)
time.sleep(1)
t = threading.Thread(target=f)
t.start()
当我按下 "start program" 按钮时,它会启动一个 5 秒的任务并阻止 GUI。
据我所知,我需要使用线程,这样每个按钮都可以独立于 GUI 工作。
我已经被困了将近一个月了,谁能告诉我如何执行 def start_Button(self)
: function using threading?
from tkinter import *
import time
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.var = IntVar()
self.master.title("GUI")
self.pack(fill=BOTH, expand=1)
quitButton = Button(self, text="Exit", command=self.client_exit)
startButton = Button(self, text="Start Program", command=self.start_Button)
quitButton.grid(row=0,column=0)
startButton.grid(row=0, column=2)
def client_exit(self):
exit()
def start_Button(self):
print('Program is starting')
for i in range (5):
print(i)
time.sleep(1)
root = Tk()
root.geometry("200x50")
app = Window(root)
root.title("My Program")
root.mainloop()
在您第一次进入线程之前,有很多重要的问题要问,但总的来说最重要的问题是 "how do I want to communicate between my threads?"在您的最小示例中,您不需要任何沟通所有,但是在您的真实代码中 start_Button
可能正在做一些工作并将数据返回给 GUI。如果是这样的话,你还有更多的工作要做。如果是这种情况,请在评论中加以澄清。
对于最小的例子,其实很简单。
class Window(tkinter.Frame):
# the rest of your GUI class as written, but change...
def start_Button(self):
def f():
# this is the actual function to run
print('Program is starting')
for i in range (5):
print(i)
time.sleep(1)
t = threading.Thread(target=f)
t.start()