在Jupyter笔记本中,如何在tqdm手动进度条完成后更改其颜色?

3

我想在Jupyter笔记本中使用tqdm的手动进度条来处理嵌套循环。为了对所有迭代进行概述,我使用以下手动更新进度条的方法:

from tqdm.notebook import tqdm

a = range(100)
b = range(5)
pbar = tqdm(total=len(a)*len(b))

for a_ in a:
  for b_ in b:
    pbar.update(1)
    pbar.refresh()

进度条

然而,当达到总迭代次数(即100%)时,颜色仍然是蓝色。但如果我使用类似于 for i in trange(100): ... 这样的代码,完成后进度条会变为绿色。

有人能告诉我如何实现手动进度条相同的行为吗?感谢帮助!

3个回答

3

我认为pbar.close()可以做到这一点。

from tqdm.notebook import tqdm

a = range(100)
b = range(5)
pbar = tqdm(total=len(a)*len(b))

for a_ in a:
  for b_ in b:
    pbar.update(1)
    pbar.refresh()
pbar.close()

0

在stackoverflow上找到了这段代码:

def progress_function(chunk, file_handling, bytes_remaining):
 '''
 function to show the progress of the download
 '''
 global filesize
 filesize=chunk.filesize
 current = ((filesize - bytes_remaining)/filesize)
 percent = ('{0:.1f}').format(current*100)
 progress = int(50*current)
 status = '█' * progress + '-' * (50 - progress)

您可以将此代码编辑为:

def progress_function(chunk, file_handling, bytes_remaining):
  '''
  function to show the progress of the download
  '''
  global filesize
  filesize=chunk.filesize
  current = ((filesize - bytes_remaining)/filesize)
  percent = ('{0:.1f}').format(current*100)
  progress = int(50*current)
  status = '█' * progress + '-' * (50 - progress)
  #change the color of the progress bar to green when the download is complete
  if bytes_remaining == 0:
      status = '\033[92m' + status + '\033[0m'
  sys.stdout.write(' ↳ |{bar}| {percent}%\r'.format(bar=status, 
      percent=percent))
  sys.stdout.flush()

当进度完成时,这将把进度条变为绿色。 我不知道它是否会对你有帮助。但是,无论如何都要看一下 :)


0
如上所述,调用close()方法就足够了。或者你可以更改color属性。就像这样:
import time
from tqdm.notebook import tqdm

total = 5
progress_bar = tqdm(total=total)
for i in range(total):
  progress_bar.update()
  time.sleep(1)

progress_bar.colour = "#00FF00"  # Bright Green
progress_bar.refresh()  # Optional

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接