本文目录导读:
是的,以下是几个Python实现倒计时功能的案例代码:
案例1:简单的命令行倒计时
import time
def countdown(t):
"""
简单的倒计时函数
:param t: 倒计时秒数
"""
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end='\r')
time.sleep(1)
t -= 1
print('时间到!')
# 使用示例
countdown(10) # 10秒倒计时
案例2:带输入功能的倒计时
import time
def input_countdown():
"""用户输入时间的倒计时"""
try:
seconds = int(input("请输入倒计时秒数:"))
for i in range(seconds, 0, -1):
print(f"剩余时间:{i}秒", end='\r')
time.sleep(1)
print("\n时间到!")
except ValueError:
print("请输入有效的数字")
input_countdown()
案例3:精确到毫秒的倒计时
import time
import datetime
def precise_countdown(seconds):
"""
精确到毫秒的倒计时
:param seconds: 倒计时秒数(可以是小数)
"""
end_time = datetime.datetime.now() + datetime.timedelta(seconds=seconds)
while True:
remaining = end_time - datetime.datetime.now()
if remaining.total_seconds() <= 0:
break
# 格式化为 分:秒.毫秒
total_seconds = remaining.total_seconds()
mins = int(total_seconds // 60)
secs = int(total_seconds % 60)
millis = int((total_seconds % 1) * 1000)
timer = f'{mins:02d}:{secs:02d}.{millis:03d}'
print(timer, end='\r')
time.sleep(0.01) # 每10毫秒更新一次
print('\n时间到!')
# 使用示例
precise_countdown(5.5) # 5.5秒倒计时
案例4:图形界面倒计时(使用tkinter)
import tkinter as tk
import time
class CountdownApp:
def __init__(self, master):
self.master = master
master.title("倒计时")
master.geometry("200x100")
self.label = tk.Label(master, text="", font=("Arial", 24))
self.label.pack(pady=20)
self.time_left = 10
self.update_display()
def update_display(self):
"""更新显示"""
if self.time_left > 0:
self.label.config(text=f"{self.time_left}秒")
self.time_left -= 1
self.master.after(1000, self.update_display)
else:
self.label.config(text="时间到!")
# 运行程序
root = tk.Tk()
app = CountdownApp(root)
root.mainloop()
案例5:多线程倒计时(可同时执行其他任务)
import time
import threading
def countdown_thread(name, seconds):
"""倒计时线程函数"""
print(f"{name}开始倒计时:{seconds}秒")
while seconds > 0:
print(f"{name}: {seconds}")
time.sleep(1)
seconds -= 1
print(f"{name}结束!")
# 创建多个倒计时线程
thread1 = threading.Thread(target=countdown_thread, args=("计时器1", 5))
thread2 = threading.Thread(target=countdown_thread, args=("计时器2", 8))
# 启动线程
thread1.start()
thread2.start()
# 主线程继续执行其他任务
for i in range(3):
print(f"主线程正在工作...{i}")
time.sleep(1)
# 等待所有线程完成
thread1.join()
thread2.join()
print("所有线程完成")
使用建议:
- 简单场景:使用案例1或案例2
- 需要精确计时:使用案例3
- 需要可视化界面:使用案例4
- 需要并行处理:使用案例5
这些案例涵盖了从简单到复杂的倒计时实现,可以根据具体需求选择合适的方案。
标签: Python案例