Skip to main content
 首页 » 编程设计

python之我的程序没有更新它的输出

2025年04月02日14JustinYoung

<分区>

我正在尝试制作一种简单的进度条,每半秒百分比就会上升;输出不断 self 更新。为此,我尝试使用 '\r' 参数,但代码只是忽略它并一遍又一遍地打印进度条,直到它达到 100%。

代码如下:

import time 
def progressBar(value, endvalue, bar_length=20): 
    while value <= endvalue: 
        percent = float(value) / endvalue 
        arrow = '-' * int(round(percent * bar_length)-1) + '>' 
        spaces = ' ' * (bar_length - len(arrow)) 
        print("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100)))) 
        value+=1 
        time.sleep(0.5) 
 
progressBar(1, 100) 

输出:

Percent: [>                   ] 1% 
 
Percent: [>                   ] 2% 
 
Percent: [>                   ] 3% 
 
Percent: [>                   ] 4% 
 
Percent: [>                   ] 5% 
 
Percent: [>                   ] 6% 
 
Percent: [>                   ] 7% 
 
Percent: [->                  ] 8% 
 
Percent: [->                  ] 9% 
 
Percent: [->                  ] 10% 
 
Percent: [->                  ] 11% 

等等等等。

有人能告诉我这里有什么问题吗?