回车不在IDLE工作?

时间:2016-03-03 09:32:07

标签: python python-3.x python-idle

我正在尝试为倒数计时器创建一个代码保持原位:这样每行都会覆盖前一行。这就是我到目前为止所做的:

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...

为什么回车似乎不起作用?

2 个答案:

答案 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

如果你在Unix终端或Windows控制台中启动Python REPL,

\r应该有用。