如何在ttk中创建下载进度条?
我想在使用 urllib.urlretrive 方法从网络下载文件时显示进度条。
如何使用 ttk.Progressbar 来完成此任务?
这是我到目前为止所做的:
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()
但它只是不断循环。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对于确定模式,您不想调用
start
。相反,只需配置小部件的值
或调用step
方法即可。如果您事先知道要下载多少字节(我假设您知道,因为您使用的是确定模式),最简单的方法是将
maxvalue
选项设置为您要下载的数字要去读书了。然后,每次读取一个块时,您都将value
配置为读取的字节总数。然后进度条将计算出百分比。下面是一个模拟,可以让您有一个粗略的了解:
要使其正常工作,您需要确保不会阻塞 GUI 线程。这意味着您要么分块读取(如示例中所示),要么在单独的线程中读取。如果您使用线程,您将无法直接调用进度条方法,因为 tkinter 是单线程的。
您可能会在 进度条示例 >tkdocs.com 很有用。
For determinate mode you do not want to call
start
. Instead, simply configure thevalue
of the widget or call thestep
method.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 thevalue
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:
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.
You might find the progressbar example on tkdocs.com to be useful.
我为你简化了代码。
将 50 替换为下载百分比。
I simplified the code for you.
Replace 50 with the percentage of the download.
如果您只是想要一个进度条来显示程序正忙/正在工作,只需将模式从确定更改为不确定
If you just want a progress bar to show that the program is busy/working just change the mode from determinate to indeterminate
这是另一个简单的示例,也显示了进度条的移动。 (我简化了 https://gist.github.com/kochie/9f0b60384ccc1ab434eb)
Here's another simple example that also shows a progress bar moving. (I have simplified the examples given at https://gist.github.com/kochie/9f0b60384ccc1ab434eb)
用于较大项目的带有进度条的模态对话框窗口
这个示例有点长,但在 Python 3.6 上进行了测试,可以在较大的项目中使用。
Modal dialog window with Progressbar for the bigger project
This example is a bit long, but tested on Python 3.6 and can be used in the bigger project.