在函数为don后,按钮调用的线程不退出

2024-05-19 18:19:31 发布

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

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

我正在尝试创建一个相当简单的Tkinter窗口来自动化GoogleLighthouse 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


Tags: pathurlifosfilename线程globalstart
1条回答
网友
1楼 · 发布于 2024-05-19 18:19:31

多亏了@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)

相关问题 更多 >