Show a custom value next to the bar¶
Sometimes the bar’s own progress isn’t the only number worth showing –
a current filename, a running total, or any other value your loop
computes – and that value doesn’t come from value/max_value at
all.
"""Recognize `DynamicMessage` in old code as today's `Variable`.
Older code may still import `DynamicMessage` -- it is a plain subclass of
`Variable` kept for compatibility, not a different widget. Prefer
`Variable` in new code; this example updates one of each, side by side
from the same value, to show they behave identically.
"""
import random
import time
import progressbar
random.seed(0)
STEPS = 24
def main() -> None:
widgets = [
progressbar.Percentage(),
' ',
progressbar.Bar(),
' ',
progressbar.Variable('current'),
' ',
progressbar.DynamicMessage('legacy'),
]
with progressbar.ProgressBar(max_value=STEPS, widgets=widgets) as bar:
for step in range(STEPS):
value = random.random()
bar.update(step + 1, current=value, legacy=value)
time.sleep(0.005)
if __name__ == '__main__':
main()
Variable(name) renders a named entry from bar.update()’s keyword
arguments: pass current=some_value to update() and a
Variable('current') widget picks it up on the next redraw. You don’t
need to seed it in advance – the bar scans its widget list at
construction and registers a placeholder for every named variable that
isn’t already supplied, so the first render shows dashes rather than
raising. Older code may import DynamicMessage instead: it is a plain
subclass of Variable, kept only so existing imports keep working, and
behaves identically – prefer Variable in anything new.