首页 > 解决方案 > while循环覆盖结果

问题描述

我正在编写简单的代码来倒计时并且无法覆盖时间。结果以一行形式出现(如 00:00:0200:00:01),我希望它堆叠起来看起来像一个实际的时钟

print(time_left,end="")

这就是我所做的,我已经\r

print("time_left + "\r", end="")

没有成功

import time
while True:
    uin = input(">> ")
    try:
            when_to_stop = abs(int(uin))
    except KeyboardInterrupt:
            break
    except:
            print("Not a number!")

while when_to_stop > 0:
        m, s = divmod(when_to_stop, 60)
        h, m = divmod(m, 60)

           #.zfill(2) to make 00:00:00 form
        time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)
        print(time_left + '\r', + end="")
        time.sleep(1)
        when_to_stop -= 1 

print()

标签: pythonpython-3.xloopswhile-looppython-3.7

解决方案


你需要使用

print(time_left,end='\r')

end='\r'将光标返回到行首。因此,当您再次打印相同的内容时,它会覆盖。


推荐阅读