You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于tqdm实现带百分比显示的进度条(附参考代码)

带百分比展示的tqdm进度条实现方法

tqdm默认自带百分比展示能力,不需要额外做复杂适配,百分比数值会根据已完成工作量和总工作量的比值自动计算显示,具体实现步骤如下:

  • 先安装tqdm依赖:执行命令pip install tqdm
  • 根据使用场景导入对应tqdm类:终端用的普通进度条导入from tqdm import tqdm,图形界面进度条导入from tqdm.gui import tqdm as tqdm_gui
  • 初始化进度条时指定total参数,参数值为你整个任务的总工作量
  • 任务每完成一部分就调用update(增量值)方法,传入本次完成的工作量,tqdm会自动计算已完成占比并展示

可运行示例代码

普通终端进度条

from tqdm import tqdm
import time

# total设为100,进度比例直接和百分比对应
with tqdm(total=100) as pbar:
    for _ in range(10):
        # 模拟任务执行逻辑
        time.sleep(0.5)
        # 本次完成10%的工作量
        pbar.update(10)

GUI版进度条(和你提供的参考代码对应)

from tqdm.gui import tqdm as tqdm_gui
import time

with tqdm_gui(total=100) as pbar:
    current_progress = 0
    while current_progress < 100:
        time.sleep(0.5)
        current_progress += 10
        pbar.update(10)

如果需要自定义百分比的显示格式,可以通过bar_format参数调整,示例如下:

# 把百分比放在进度条最前方展示
with tqdm(total=100, bar_format='{percentage:3.0f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}]') as pbar:
    # 你的任务逻辑
    pass

内容的提问来源于stack exchange,提问作者DoggoPlayer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:15:03