【发布时间】:2020-06-25 11:08:35
【问题描述】:
我正在尝试在 tkinter Progressbar 中显示下载的图像,它正在工作,但进度条在所有图像下载完成之前完成。我问了一个非常相似的问题tkinter updating progress bar on thread progress,我的想法是根据使用len(os.listdir('.')) 创建的文件数量来更新进度条。
import tkinter
from tkinter.ttk import Progressbar
import os,uuid,requests,threading
import numpy as np
def bar():
temp = 0
for lst in chunks:
threads.append(threading.Thread(target=download_image, args=(lst)))
for x in threads:
x.start()
while temp<len(links):
progress['value'] = temp
root.update_idletasks()
temp =len(os.listdir('.'))
print("closing threads")
for i in threads:
i.join()
temp =len(os.listdir('.'))
progress['value'] = temp
print('done')
root.destroy()
with open('image_urls.txt','r') as f:
links = f.read().split('\n') #links to image urls
threads =[]
chunks = [i.tolist() for i in np.array_split(links, 10) if i.size>0]
root = tkinter.Tk()
root.geometry("400x300")
root.title('Downloader v1')
progress = Progressbar(root, orient = tkinter.HORIZONTAL,
length = 250, mode = 'determinate',maximum=len(links))
progress.pack(pady = 100)
notice = tkinter.Label(root, text=str(len(links)),
fg="grey2",)
notice.place(x=350, y=100)
compose_button = tkinter.Button(root, text = 'Start', command = bar)
compose_button.pack()
root.mainloop()
【问题讨论】:
-
您使用的是
maximum=len(links)),但使用progress['value'] = temp可能不一样。此外,您的def bar(...使用while temp<len(links):和.join()阻塞。阅读While Loop Locks Application -
@stovfl [docs.python.org/3/library/tkinter.ttk.html](docs) 说
maximum是进度条的最大值,我只是给它计数,(理想情况下)计数应该完成(在while循环中)在加入线程之前。 -
"maximum 是进度条的最大值,":这不是重点。我可以在
temp =len(os.listdir('.'))之后看到print(maximum)和print(temp)的输出吗? -
@stovfl 输出为“无限”,但它从 0 开始并以
len(links)结束,但是len(os.listdir('.'))显示的数量与实际数量不同(我正在刷新文件夹并且值不匹配) -
"and values don't match":这就是我的意思,差别有多大。比
len(links)多还是少?
标签: python multithreading tkinter