倒计时:01:05 [英] Countdown Clock: 01:05
问题描述
如何在 Python 中创建一个看起来像 00:00(分 & 秒)的倒计时时钟,它在自己的一行上.每次它减少一实际秒,那么旧的计时器应该在其行上替换为一个低一秒的新计时器:01:00
变成了 00:59
并且它实际上命中了 00:00
.
How can I create a countdown clock in Python that looks like 00:00 (min & sec) which is on a line of its own. Every time it decreases by one actual second then the old timer should be replaced on its line with a new timer that is one second lower:
01:00
becomes 00:59
and it actually hits 00:00
.
这是我开始使用但想要转换的基本计时器:
Here is a basic timer I started with but want to transform:
def countdown(t):
import time
print('This window will remain open for 3 more seconds...')
while t >= 0:
print(t, end='...')
time.sleep(1)
t -= 1
print('Goodbye! \n \n \n \n \n')
t=3
我还想确保 Goodbye!
之后的任何内容(最有可能在函数之外)都在它自己的行上.
I also want to make sure that anything after Goodbye!
(which would most likely be outside of the function) will be on its own line.
结果: 3...2...1...0...再见!
我知道这与其他倒计时问题类似,但我相信它有其独特之处.
I know this is similar to other countdown questions but I believe that it has its own twist.
推荐答案
除了将时间格式化为分钟和秒之外,您还需要打印回车.将 end
设置为 \r
:
Apart from formatting your time as minutes and seconds, you'll need to print a carriage return. Set end
to \r
:
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('Goodbye!\n\n\n\n\n')
这可确保 next 打印覆盖最后一行打印:
This ensures that the next print overwrites the last line printed:
这篇关于倒计时:01:05的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!