请求开发含分/秒/毫秒的倒计时计时器(附现有代码)
支持分钟、秒、毫秒的Python倒计时计时器
下面是修改后的代码,实现了包含分钟、秒、毫秒的精确倒计时:
import time def countdown(total_ms): while total_ms > 0: # 分解分钟、秒、毫秒 mins = total_ms // (60 * 1000) remaining_ms = total_ms % (60 * 1000) secs = remaining_ms // 1000 ms = remaining_ms % 1000 # 格式化输出,分钟两位、秒两位、毫秒三位 time_format = '{:02d}:{:02d}:{:03d}'.format(mins, secs, ms) print(time_format, end='\r') # 休眠1毫秒 time.sleep(0.001) total_ms -= 1 print("stop") # 示例:倒计时3分钟(3*60*1000=180000毫秒) countdown(180000)
关键修改说明:
- 将函数参数改为总毫秒数,以此实现毫秒级精度的倒计时控制
- 通过逐层计算,从总毫秒数中分解出分钟、秒和剩余毫秒
- 格式化字符串新增毫秒位,用
{:03d}保证三位数字显示 - 调整休眠时间为
0.001秒(即1毫秒),每次循环递减1毫秒 - 循环条件判断总毫秒数大于0,确保倒计时完全结束
内容的提问来源于stack exchange,提问作者MThien
相关产品推荐
相关产品推荐

