thread与tkin的离奇退出行为

2024-09-25 00:22:59 发布

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

我正在尝试一个GUI应用程序,在这个应用程序中,我使用线程来创建并发执行的任务。代码如下:

from tkinter import *
from threading import *
import time
kill = False

def mainer():
    global kill
    while not kill:
        maintext.set(value='bbb')


def quitfunc():
    global kill
    kill = True
    time.sleep(2)
    root.destroy()



root=Tk()
maintext=StringVar(value='aaa')
Thread(target=mainer).start()
root.protocol("WM_DELETE_WINDOW", quitfunc)
root.mainloop()

问题:

  1. 根进程不会停止,因为它当前正在关闭窗口。它一直在跑。即使我为mainer线程添加一个无限循环来打印isalive(),它也会一直说True。为什么它不退出?
  2. 如果我在mainer函数中添加print(kill)语句,则会得到两个结果之一:
    1. 如果写在maintext.set()语句之上,则在退出窗口时,打印停止执行,但线程仍然没有退出。很少有这样的情况,我假设这取决于执行quit函数时函数所在的行。在
    2. 如果写在下面,那么在退出时,线程几乎不可避免地会退出。在

我不知道这里发生了什么事。感谢任何帮助。在


Tags: 函数fromimport应用程序timevaluedefroot
1条回答
网友
1楼 · 发布于 2024-09-25 00:22:59

如果将线程设为守护进程,则当主线程终止时,它将消亡,因此您根本不需要任何退出逻辑:

from tkinter import *
from threading import *
import time

def mainer():
    while True:
        maintext.set(value='bbb')
    time.sleep(.1) # just so my CPU does not rail

root=Tk()
maintext=StringVar(value='aaa')
t = Thread(target=mainer)
t.daemon = True
t.start()
root.mainloop()

相关问题 更多 >