Tkinter python多线程(避免“不响应”)
我正试图用tkinter编写一个Python GUI程序 我想做两根线。一个使用main_form函数运行,以防止tkinter保持更新和循环(避免“无响应”) 另一方面,单击按钮1(btn1)时,使函数sci_thread()开始运行,并启动thread2,该函数使用长时间代码执行主scikit 但特金特一直没有回应 下面是我的代码:Tkinter python多线程(避免“不响应”),python,tkinter,Python,Tkinter,我正试图用tkinter编写一个Python GUI程序 我想做两根线。一个使用main_form函数运行,以防止tkinter保持更新和循环(避免“无响应”) 另一方面,单击按钮1(btn1)时,使函数sci_thread()开始运行,并启动thread2,该函数使用长时间代码执行主scikit 但特金特一直没有回应 下面是我的代码: import threading class class_one: def main_scikit(seft): ######
import threading
class class_one:
def main_scikit(seft):
######
code_take_loooong_time
######
def save(seft):
pass
def main_form(seft):
root = Tk( )
root.minsize(width=300, height=500)
ent1 = Entry(width=30)
ent1.grid(row=0,column=1,padx = 10,pady=5)
bnt1 = Button(root,text = "Start",command=lambda : seft.sci_thread())
bnt1.grid(row=5,column=0,padx = 10)
root.update()
root.mainloop()
def sci_thread(seft):
maincal = threading.Thread(2,seft.main_scikit())
maincal.start()
co = class_one()
mainfz = threading.Thread(1,co.main_form());
mainfz.start()
您的应用程序没有响应,因为您的目标参数在声明时执行,其结果作为目标传递。而且,很明显,因为GUI在GUI线程中执行
code\u take\u loooong\u time
时没有响应。为了解决这个问题,去掉多余的括号
请尝试以下代码段:
import threading
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
class class_one:
def main_scikit(self):
######
# code_take_loooong_time
# same as sleep
threading.Event().wait(5)
# some print
self.print_active_threads_count()
######
def save(self):
pass
def main_form(self):
self.root = tk.Tk()
self.root.minsize(width=300, height=500)
self.ent1 = tk.Entry(self.root, width=30)
self.ent1.grid(row=0, column=1, padx=10, pady=5)
self.bnt1 = tk.Button(self.root, text="Start", command=self.sci_thread)
self.bnt1.grid(row=5, column=0, padx=10)
self.root.update()
self.root.mainloop()
def sci_thread(self):
maincal = threading.Thread(target=self.main_scikit)
maincal.start()
def print_active_threads_count(self):
msg = 'Active threads: %d ' % threading.active_count()
self.ent1.delete(0, 'end')
self.ent1.insert(0, msg)
print(msg)
co = class_one()
mainfz = threading.Thread(target=co.main_form)
mainfz.start()
链接:
mainloop
是最外层的循环,并且所有Tcl命令都是从同一线程调用的。因此,可能会有许多和更多的同步问题,所有这些!
总而言之,也许这会给你一些新的想法。@erosennin113,请让你的代码可以为PEEP运行,你不能像那样声明线程,但是试着
mainfz=threading.Thread(target=co.main_form)
。我不知道你的code\u take\u loooong\u time
到底是什么,但是有了正确的线程声明和main\u scikit
中的一些时间循环,它工作得很好-GUI负责,我可以用它创建任意多的线程。所以,花一些时间在你的代码上,使其完整并确认问题不再存在,好吗?谢谢@CommonSense抱歉我不能在这里发布代码,我正在进行scikit学习,在code\u take\u looong\u time
中,一些数据分析功能大约需要500-2000秒。在此期间,我有一些打印功能,可以在GUI的文本字段中报告。但是UI没有响应时间code\u take\u looong\u time
take。最后,打印函数excute一切正常。您是否阅读了我关于正确声明线程的建议?首先,您只需要一个参数target
,并且target必须是可调用的。换句话说,在线程开始之前调用并执行scikit learn的例程。这和为什么在声明按钮时使用lambda的原因相同-只是为了阻止该函数的执行。Ty@CommonSense,但是,我不能让它工作:(,我声明的就像你说的。另一部分,我如何防止scikit在线程启动之前不会执行。