Han*_*nix 28 python tkinter ttk
我想在使用该urllib.urlretrive方法从Web下载文件时显示进度条.
我如何使用它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()
Run Code Online (Sandbox Code Playgroud)
但它只是不断循环.
Bry*_*ley 34
对于确定模式,您不想打电话start.相反,只需配置value小部件或调用step方法即可.
如果您事先知道要下载多少字节(我假设您在使用确定模式时这样做),最简单的方法是将maxvalue选项设置为您要读取的数字.然后,每次读取一个块时,value都要将其配置为读取的总字节数.然后进度条将计算百分比.
这是一个模拟,给你一个粗略的想法:
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()
Run Code Online (Sandbox Code Playgroud)
为此,您需要确保不阻止GUI线程.这意味着你要么读取块(如示例中所示),要么在单独的线程中读取.如果使用线程,则无法直接调用progressbar方法,因为tkinter是单线程的.
您可能会发现在进度例如上tkdocs.com是有用的.
我为你简化了代码.
import sys
import ttk
from Tkinter import *
mGui = Tk()
mGui.geometry('450x450')
mGui.title('Hanix Downloader')
mpb = ttk.Progressbar(mGui,orient ="horizontal",length = 200, mode ="determinate")
mpb.pack()
mpb["maximum"] = 100
mpb["value"] = 50
mGui.mainloop()
Run Code Online (Sandbox Code Playgroud)
将50替换为下载百分比.
小智 5
如果您只是想要一个进度条来显示程序正忙/正在工作,只需将模式从确定更改为不确定
pb = ttk.Progressbar(root,orient ="horizontal",length = 200, mode ="indeterminate")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68244 次 |
| 最近记录: |