【发布时间】:2016-12-22 13:47:53
【问题描述】:
我正在尝试制作一种简单的进度条,每半秒百分比就会上升;输出不断自我更新。为此,我尝试使用 '\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%
等等等等。
谁能告诉我这里有什么问题?
【问题讨论】:
-
对于箭头变量,您缺少与 100 的乘法
-
print() 将在要打印的消息之后附加换行符。试试
print("Percent: ...", end='\r')。 -
它只是打印所有内容,就像我写的一样 (end=' ')
-
可能是因为你使用的IDE,在控制台中测试一下。
-
在控制台上试过,一样
标签: python