1. 程式人生 > >Python中製作帶數字的進度條

Python中製作帶數字的進度條

簡單製作一個進度條,效果如下:

不多說,直接上程式碼:

import time
EACH_STEP_COST_TIME = 0.3
PROCESS_TOTAL_STEP = 40

def process_bar(current_state, total_state, bar_length=20):
    bar = ['['] + ['-'] * bar_length + [']']
    current_bar = int(current_state/total_state*bar_length)
    for j in range(current_bar+1):
        bar[j+1] = '#'
    bar_show = ''.join(bar)
    print('\r{}%d%%'.format(bar_show) % ((current_state+1)/total_state*100), end='')
    if current_state == total_state-1:
        bar = ['['] + ['#'] * bar_length + [']']
        bar_show = ''.join(bar)
        print('\r{}%d%%'.format(bar_show) % 100, end='')
        print('\r')


print("Progress start:")
for step in range(PROCESS_TOTAL_STEP):
    process_bar(step, PROCESS_TOTAL_STEP)
    time.sleep(EACH_STEP_COST_TIME)
print("Process finished.")