根目录。销毁不终止在sh中运行的线程

2024-04-20 09:53:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图以正确的方式关闭我的应用程序,但我可能做得不正确,我所拥有的似乎不符合要求。在

我有正常的

command = root.destroy

它关闭了图形用户界面,但我仍然有线程在运行,似乎继续在打印在外壳!在

下面是“不朽”的线程

^{pr2}$

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

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

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

我哪里出错了?在

提前谢谢你。在

另外,伦敦今天阳光明媚!在


Tags: text应用程序close方式guibuttonroot外壳
1条回答
网友
1楼 · 发布于 2024-04-20 09:53:35

首先,您应该使用^{}模块,而不是^{cd2>}模块,如the docs中所建议的^{cd2>}模块:

Note: The thread module has been renamed to _thread in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3; however, you should consider using the high-level threading module instead.

也就是说,有几个解决问题的方法:

一种方法是使用^{cd4>}对象,并将其设置为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中的默认类型)将继续运行,即使主线程完成,而且您的程序将不会退出,直到非守护进程线程自己退出。

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

^{pr2}$

然后在您的主线程中:

^{pr3}$

这有一个好处,让您优雅地关闭线程。使用^{cd5>}将立即终止线程,如果线程处于某个中间(例如,编写某些内容或持有一些不会自动释放的资源),这可能会很糟糕。^{cd1>}文档make a note of this as well

Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

相关问题 更多 >