我正在尝试为倒数计时器创建一个代码保持原位:这样每行都会覆盖前一行。这就是我到目前为止所做的:
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timeformat = "{:02d}:{:02d}".format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
print("That's the end! You lose...\n\n\n\n\n")
exit()
countdown(10)
然而,输出是:
00:10
00:09
00:08
...
00:00
That's the end! You lose...
为什么回车似乎不起作用?
答案 0 :(得分:1)
当\r
不起作用时,请尝试\x08
(退格),并添加flush=True
以确保安全:
print('\x08' * 5 + timeformat, end='', flush=True)
答案 1 :(得分:1)
IDLE doesn't support most control characters such as \r
, \b
\r
应该有用。