SoFunction
Updated on 2025-03-05

Summary of various methods to implement progress bars in Python

1. Simple printing method

This is the most straightforward way to simulate a progress bar by printing characters in a loop. Although this method is limited in functionality, it is very easy to understand and implement.

import time
import sys
 
def simple_progress_bar(total_steps):
    for i in range(total_steps + 1):
        percent = (i / total_steps) * 100
        bar = '#' * int(percent / 10)
        (f"\r[{bar:<10}] {percent:.2f}%")
        ()
        (0.1)  # Simulation tasks take time    print("\nDone!")
 
#User Examplesimple_progress_bar(100)

In this example, and is used to update the progress bar in real time on the console, while the \r character is used to move the cursor back to the beginning of the line, thus overwriting the previous progress bar.

2. Use the tqdm library

tqdm is a very popular Python progress bar library that provides a simple and easy-to-use API that can be easily used with various iterators and loops.

from tqdm import tqdm
import time
 
# Use tqdm to wrap an iterable objectfor i in tqdm(range(100), desc="Processing"):
    (0.1)  # Simulation tasks take time 
# Or use manual update modepbar = tqdm(total=100, desc="Manual")
for i in range(100):
    (0.1)  # Simulation tasks take time    (1)   # Update progress()

The tqdm library not only supports basic progress bar display, but also provides a variety of customization options, such as nested progress bars, dynamic adjustment of speed, etc.

3. Use the alive-progress library

alive-progress is another powerful library of progress bars that provide rich animation effects and a highly customizable interface.

from alive_progress import alive_bar
import time
 
# Create progress bars with alive_barwith alive_bar(100, title="Alive Progress") as bar:
    for i in range(100):
        (0.1)  # Simulation tasks take time        bar()            # Update progress bar 
# You can also add custom animations and formatsfrom alive_progress.styles import Spinner
 
with alive_bar(100, title="Custom Style", bar_type='filling_squares', spinner=Spinner.dots12) as bar:
    for i in range(100):
        (0.1)
        bar()

The alive-progress library also supports multi-threading and multi-process tasks, which can provide intuitive progress feedback in complex application scenarios.

4. Use the progress library

The progress library provides multiple progress bar styles and supports nested progress bars and dynamic updates.

from  import Bar
import time
 
bar = Bar('Processing', max=100)
for i in range(100):
    (0.1)  # Simulation tasks take time    ()       # Update progress bar()
 
#Nested progress bar exampleouter_bar = Bar('Outer Progress', max=10)
for i in range(10):
    inner_bar = Bar(f'Inner Progress {i+1}', max=10)
    for j in range(10):
        (0.1)
        inner_bar.next()
    inner_bar.finish()
    outer_bar.next()
outer_bar.finish()

The progress library is suitable for application scenarios where complex nested progress bars are required. It provides a flexible API to meet various needs.

5. Use the progress bar function of the click library

click is a Python library for creating command line interfaces, which also provides simple progress bar functionality.

import click
import time
 
@()
def process():
    with (range(100), label='Processing') as bar:
        for i in bar:
            (0.1)  # Simulation tasks take time 
if __name__ == '__main__':
    process()

Using the progress bar feature of the click library, you can easily create applications with command line interfaces and provide intuitive progress feedback.

6. Custom progress bar class

If you need a highly customized progress bar, you can create your own progress bar class. This approach, while requiring more code, provides maximum flexibility.

import sys
import time
 
class CustomProgressBar:
    def __init__(self, total, length=50):
         = total
         = length
         = 0
 
    def update(self, step=1):
         += step
        percent = ( / ) * 100
        bar = '#' * int(percent *  / 100)
        (f"\r[{bar:<{}}] {percent:.2f}%")
        ()
 
    def finish(self):
        print("\nDone!")
 
#User Examplepbar = CustomProgressBar(100)
for i in range(100):
    (0.1)  # Simulation tasks take time    ()    # Update progress bar()        # End progress bar

Customize the progress bar class, you have complete control over the appearance and behavior of the progress bar to meet the needs of a specific application.

7. Combined with the GUI library to implement progress bar

If you are developing a graphical user interface (GUI) application, you can combine GUI libraries (such as tkinter, PyQt, etc.) to implement the progress bar.

import tkinter as tk
from tkinter import ttk
import time
 
def process():
    for i in range(101):
        bar['value'] = i  # Update progress bar value        root.update_idletasks()  # Update the GUI interface        (0.1)  # Simulation tasks take time 
# Create the main windowroot = ()
("GUI Progress Bar")
 
# Create a progress barbar = (root, orient="horizontal", length=300, mode="determinate")
(pady=20)
 
# Start processing tasks(0, process)
 
# Run the main loop()

In this example, we created a simple GUI application using the tkinter library and added a progress bar control to it. The dynamic display of the progress bar is achieved by updating the value of the progress bar and calling the update_idletasks method after each update.

8. Summary

This article introduces a variety of ways to implement progress bars in Python, including simple printing methods, using popular third-party libraries (such as tqdm, alive-progress, progress and click), custom progress bar classes and combining GUI libraries to implement progress bars. Each method has its own unique advantages and applicable scenarios. You can choose the appropriate method according to your specific needs to implement the progress bar function. Hopefully these sample codes and cases can help you better understand and apply progress bar technology.

The above is the detailed content of various ways to implement progress bars in Python. For more information about Python implementation progress bars, please pay attention to my other related articles!