python - 函数完成后,按钮调用的线程不会退出

标签 python tkinter python-multithreading

Python 版本 3.7 | NPM 版本 6.2.0 | Google Lighthouse 软件包版本 4.0.0

我正在尝试创建一个相当简单的 Tkinter 窗口来自动化 Google lighthouse NPM 包,但在尝试停止线程时失败了。

主题:

lighthouse_thread = threading.Thread(target=start_lighthouse)

启动线程的按钮:

Start_Ligthouse = Button(root, text="Starten", command=lighthouse_thread.start)
Start_Ligthouse.place(x=850, y=312)
Start_Ligthouse.config(state=DISABLED)
root.after(100, CheckInOut)

该函数如下所示:

def start_lighthouse():                                                                                                                                         
    global filenumber
    global reportlocation
    global instantkill
    global file

    Start_Ligthouse.config(state=DISABLED)   
    for url in file:
        url = url.rstrip("\n")
        print(url)
        filename = url.replace("https","").replace("/","-").replace("\n","").replace(":","").replace("--","")

        if os.path.isfile(reportlocation + "/" + filename + ".html"):
            print("EXISTS!")
            filenumber = 2
            while True:                                                                                                                                         
                newfilename = filename + "{}".format(filenumber)
                if not os.path.isfile(reportlocation + "/" + newfilename + ".html"):
                    filename = newfilename
                    break
                filenumber += 1
        if instantkill:
            break


        #os.system("lighthouse --disable-device-emulation --throttling-method=provided --preset=perf --quiet --output-path={}/{}.html {}".format(reportlocation,filename,url))

    CheckIn = False
    CheckOut = False
    print("LoopEnded")

我对 os.system 命令进行了注释,以便我可以快速浏览该列表。如果我再次调用该函数,我会收到线程无法启动两次的错误(我理解)。但据我所知,线程应该在函数完成后终止。

我的问题是:如何让线程在完成其应做的事情后终止?

Full code can be found here

最佳答案

感谢@JamesKent,我修复了它。

我没有使用按钮调用线程,而是创建了一个创建线程的函数。

def create_thread():
    print("Thread Created")
    lighthouse_thread = threading.Thread(target=start_lighthouse)
    lighthouse_thread.start()

按钮现在调用此函数,从而创建一个新线程。

Start_Ligthouse = Button(root, text="Starten", command=create_thread)

关于python - 函数完成后,按钮调用的线程不会退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53559502/

相关文章:

python - 运行时错误: Too early to create image

python - 我的代码另一个错误

python - 检查线程是否已在 MicroPython 中启动

python - Python 中 os.walk 的时间复杂度

python - 在多处理过程中抑制输出

python - 在 Python 中比较两个不同顺序的字典列表

python - 为什么 Photoimage put() 很慢?

python - 使用多处理/线程通过 Tkinter 读取串行端口和实时图形数据

python - 使用多线程将数据写入多个文件

python - 如何在Python中将多个直方图堆叠在一个图中?