root.destroy不会终止在shell中运行的线程

时间:2014-08-05 17:53:26

标签: python multithreading shell

我试图以正确的方式关闭我的应用程序,但我可能没有正确地做到这一点,我所拥有的似乎不符合要求。

我有正常的

command = root.destroy

关闭了GUI但我仍然运行了线程,这似乎在Shell的打印中保持明显!

以下是不朽的线程'

def trick(threadName, sleepTime):
    while 1 < 2:
         field.delete(0, END)
         field.insert(0, "Safe Mode")
         print "%s" % (threadName)
try:
    thread.start_new_thread(trick,("Safe Mode Running", 5))
except: Exception,
print "Safe mode has started"

然后我有其他部分,GUI完成如下所示:

Close = Button(text = "Close", command = root.destroy)
Close.grid(column = 21, row = 0)        

root.configure(background='#2b5bce')
root.title("Safe Mode")
root.mainloop()

我哪里错了?

提前谢谢。

P.S。这是伦敦一个阳光灿烂的日子!

1 个答案:

答案 0 :(得分:1)

首先,您应该使用threading模块而不是thread模块,如the docs中对thread模块的建议:

  

注意:线程模块已在Python 3中重命名为_thread.2to3   转换源时,工具会自动调整导入   Python 3; 但是,您应该考虑使用高级threading   而不是模块。

也就是说,有几种方法可以解决您的问题:

一种是使用threading.Thread对象并将其设置为daemonic thread

def trick(threadName, sleepTime):
    while 1 < 2:
         field.delete(0, END)
         field.insert(0, "Safe Mode")
         print "%s" % (threadName)
try:
    t = threading.Thread(target=trick, args=("Safe Mode Running", 5))
    t.daemon = True
    t.start()
except: Exception,
print "Safe mode has started"
主线程完成后,

守护程序线程将退出。非守护程序线程(这是Python中的默认类型),即使在主线程完成后也会继续运行,并且程序不会退出,直到非守护程序线程自行退出。

第二个选项是使用非守护程序线程,但告诉他们在程序准备好退出时关闭:

exiting = threading.Event()

def trick(threadName, sleepTime):
    while 1 < 2:
         if exiting.is_set():
             return
         field.delete(0, END)
         field.insert(0, "Safe Mode")
         print "%s" % (threadName)
try:
    t = threading.Thread(target=trick, args=("Safe Mode Running", 5))
    t.daemon = True
    t.start()
except: Exception,
print "Safe mode has started"

然后在你的主线程中:

Close = Button(text = "Close", command = root.destroy)
Close.grid(column = 21, row = 0)        

root.configure(background='#2b5bce')
root.title("Safe Mode")
root.mainloop()
exiting.set()  # Tell the threads to exit

这样做的好处是可以让你优雅地关闭线程。使用daemon=True将立即终止你的线程,如果他们处于某事的中间(例如写东西或持有一些不会被自动释放的资源),这可能会很糟糕。{{ 1}} docs make a note of this as well

  

守护程序线程在关闭时突然停止。他们的资源(如此   作为打开文件,数据库事务等)可能不会被释放   正常。如果你想让你的线程优雅地停止,那就制作它们吧   非守护进程并使用合适的信令机制,如事件。

相关问题