pythontqdm

Change color of tqdm for each iteration


I'm using tqdm to track the progress of a task. For the fun of it, I want to change the color of the progress bar dynamically during each iteration.

I know you can update the description of the bar using set_description(), but I haven’t found anything similar for changing the color of the progress bar. Is there a way to do that with tqdm? Something along the lines of this (pseudo-code):

from tqdm import tqdm
import time

colors = ["red", "yellow", "green", "cyan", "blue"]

pbar = tqdm(range(5))
for i in pbar:
    pbar.set_color(colors[i])
    time.sleep(0.5)

Solution

  • You can manually set the tqdm object's colour attribute:

    from tqdm import tqdm
    import time
    
    colors = iter(["red", "yellow", "green", "cyan", "blue"])
    
    pbar = tqdm(range(5))
    for i in pbar:
        pbar.colour = next(colors)
        time.sleep(0.5)