python进度条实现的几种方法
一、普通进度条(time实现)
import time
def progress_bar():
for i in range(101):
print(f'\rProgress: {"#" * i}{"." * (100 - i)} {i}%', end='')
time.sleep(0.1)
if __name__ == '__main__':
progress_bar()
展示结果:
二、带颜色、样式的进度条(colorama
)
from colorama import init, Fore, Back, Style
import time
def colored_progress_bar():
init(autoreset=True)
for i in range(101):
percentage = Fore.GREEN + f'{i}%' + Fore.RESET
filled_length = int(i // 2)
bar = Back.WHITE + Fore.BLUE + '#' * filled_length + Fore.RESET + Back.RESET + '.' * (50 - filled_length)
print(f'\r{bar} {percentage}', end='')
time.sleep(0.1)
if __name__ == '__main__':
colored_progress_bar()
展示结果:
三、简单的进度条工具包实现(tpdm)
from tqdm import tqdm
import time
def tqdm_progress_bar():
for i in tqdm(range(100)):
time.sleep(0.1)
if __name__ == '__main__':
tqdm_progress_bar()
展示结果:
四、带一点动画效果的进度条(alive_progress)
import time
from alive_progress import alive_bar
items = range(100)
with alive_bar(len(items)) as bar:
for item in items:
bar()
time.sleep(0.1)
展示结果:
五、可视化进度条(tkinter+time)
import tkinter as tk
import time
from tkinter import ttk
def gui_progress_bar():
root = tk.Tk()
root.title('进度条示例')
progressbar = ttk.Progressbar(root, orient='horizontal', length=400, mode='determinate')
progressbar.pack(pady=20)
root.update()
for i in range(101):
progressbar['value'] = i
root.update()
time.sleep(0.1)
root.destroy()
if __name__ == '__main__':
gui_progress_bar()
展示结果: