在start_new_thread后如何join线程
下面这个函数在我单独运行的时候会在3秒后结束,但当我在一个线程里调用它时,它却一直没有结束。请帮我看看这段代码有什么问题。
def display(val1, val2):
root = Tk()
clock = Label(root, font=('times', 20, 'bold'), bg='white')
clock.pack(fill=BOTH, expand=0)
def tick():
time1 = val1 +'\n' + val2
clock.config(text=time1)
tick()
root.after(3000,root.quit)
root.mainloop()
我在我的程序里是这样调用上面的函数的:
thread.start_new_thread(display,(val1,val2))
线程启动得很正常,主程序也在继续运行,但这个显示函数在3秒后并没有结束。请告诉我怎么才能让这个线程结束,或者怎么处理它而不影响主程序。
1 个回答
2
编辑:
在我的测试中,我觉得你真正的问题出在tkinter上。你应该使用 Tk.destroy()
而不是 Tk.quit()
。
from tkinter import * # < Python3.x you will need Tkinter not tkinter.
from threading import Thread
def display(val1, val2):
root = Tk()
clock = Label(root, font=('times', 20, 'bold'), bg='white')
clock.pack(fill=BOTH, expand=0)
def tick():
time1 = val1 +'\n' + val2
clock.config(text=time1)
tick()
root.after(3000, root.destroy)
root.mainloop()
thread = Thread(target=display, args=("1", "2"))
thread.start()
这个方法对我有效。
之前提到过:
你应该看看更高级的 threading
模块。这是个更好的选择。
要合并线程:
from threading import Thread
...
thread = Thread(target=display, args=(val1, val2))
thread.start()
...
thread.join()
另外一个选择是 multiprocessing
模块。
from multiprocessing import Process
...
process = Process(target=display, args=(val1, val2))
process.start()
...
process.join()
而且与 threading
或 thread
不同,multiprocessing
提供了 Process.terminate()
方法。