在start_new_thread之后加入线程

时间:2012-02-11 09:59:48

标签: python multithreading 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 个答案:

答案 0 :(得分:0)

编辑:

在我的测试中,我认为你的实际问题是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()

threadingthread不同,multiprocessing提供Process.terminate()