如何在ttk中创建下载进度条? [英] How to create downloading progress bar in ttk?
问题描述
我想在使用 urllib.urlretrive
方法从网络下载文件时显示进度条.
I want to show a progress bar while downloading a file from the web using the urllib.urlretrive
method.
我如何使用 ttk.Progressbar
来完成这个任务?
How do I use the ttk.Progressbar
to do this task?
这是我目前所做的:
from tkinter import ttk
from tkinter import *
root = Tk()
pb = ttk.Progressbar(root, orient="horizontal", length=200, mode="determinate")
pb.pack()
pb.start()
root.mainloop()
但它只是不断循环.
推荐答案
对于确定模式,您不想调用 start
.相反,只需配置小部件的 value
或调用 step
方法.
For determinate mode you do not want to call start
. Instead, simply configure the value
of the widget or call the step
method.
如果您事先知道要下载多少字节(并且我假设您这样做,因为您使用的是确定模式),最简单的做法是将 maxvalue
选项设置为你要阅读的数字.然后,每次读取块时,您都将 value
配置为读取的总字节数.然后进度条会计算出百分比.
If you know in advance how many bytes you are going to download (and I assume you do since you're using determinate mode), the simplest thing to do is set the maxvalue
option to the number you are going to read. Then, each time you read a chunk you configure the value
to be the total number of bytes read. The progress bar will then figure out the percentage.
这是一个模拟,可以让您大致了解:
Here's a simulation to give you a rough idea:
import tkinter as tk
from tkinter import ttk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.button = ttk.Button(text="start", command=self.start)
self.button.pack()
self.progress = ttk.Progressbar(self, orient="horizontal",
length=200, mode="determinate")
self.progress.pack()
self.bytes = 0
self.maxbytes = 0
def start(self):
self.progress["value"] = 0
self.maxbytes = 50000
self.progress["maximum"] = 50000
self.read_bytes()
def read_bytes(self):
'''simulate reading 500 bytes; update progress bar'''
self.bytes += 500
self.progress["value"] = self.bytes
if self.bytes < self.maxbytes:
# read more bytes after 100 ms
self.after(100, self.read_bytes)
app = SampleApp()
app.mainloop()
为此,您需要确保不会阻塞 GUI 线程.这意味着要么分块读取(如示例中所示),要么在单独的线程中读取.如果您使用线程,您将无法直接调用进度条方法,因为 tkinter 是单线程的.
For this to work you're going to need to make sure you don't block the GUI thread. That means either you read in chunks (like in the example) or do the reading in a separate thread. If you use threads you will not be able to directly call the progressbar methods because tkinter is single threaded.
您可能会在 进度条示例.com">tkdocs.com 很有用.
You might find the progressbar example on tkdocs.com to be useful.
这篇关于如何在ttk中创建下载进度条?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!