python - 功能完成后按钮调用的线程不退出
问题描述
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 命令,以便我可以快速浏览列表。如果我要再次调用该函数,我会收到线程无法启动两次的错误(我理解。)但据我所知,线程应该在函数完成后终止。
我的问题是:如何让线程在完成它应该做的事情后终止?
解决方案
感谢@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)
推荐阅读
- linux - 如何让 Linux USB 小工具和网络驱动程序相互通信
- python - 如何在 statsmodel ols 中获得“样本内”预测值(y hat)?
- sql - 来自多个 ID 的单一身份的 SQL 解决方案
- stata - 如何在Stata中找到最接近(第二接近,第三接近......)的值
- java - Hibernate中构造函数、getter和setter的顺序
- automapper - 为什么 AutoMapper 会抛出错误 AutoMapperConfigurationException?
- listview - 过滤时 ListView.builder 的索引未保留在 listTile onTap 内
- python - 使用 PIL 从 Python 3 中的图像中删除单个像素行
- sql - 如何从按日期列分区的配置单元表中获取最新日期?
- html - 如何将 HTML5 图像组织到子文件夹中?