首页 > 解决方案 > 功能完成后按钮调用的线程不退出

问题描述

Python 版本 3.7 | NPM 版本 6.2.0 | 谷歌灯塔包版本 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 命令,以便我可以快速浏览列表。如果我要再次调用该函数,我会收到线程无法启动两次的错误(我理解。)但据我所知,线程应该在函数完成后终止。

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

完整代码可以在这里找到

标签: pythontkinterpython-multithreading

解决方案


感谢@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)

推荐阅读