Python tkinter 实现十分钟的倒计时程序
时间: 2023-11-19 17:06:40 浏览: 174
下面是用Python tkinter实现10分钟倒计时程序的示例代码:
```python
import tkinter as tk
from datetime import datetime, timedelta
class CountdownTimer():
def __init__(self, master):
self.master = master
master.title("10 Minutes Countdown Timer")
master.geometry("300x100")
self.time_left = timedelta(minutes=10)
self.timer_running = False
self.label = tk.Label(master, text=self.format_time(self.time_left))
self.label.pack(pady=10)
self.start_button = tk.Button(master, text="Start", command=self.start_timer)
self.start_button.pack(side=tk.LEFT, padx=10)
self.stop_button = tk.Button(master, text="Stop", command=self.stop_timer, state=tk.DISABLED)
self.stop_button.pack(side=tk.LEFT, padx=10)
def start_timer(self):
self.timer_running = True
self.start_button.config(state=tk.DISABLED)
self.stop_button.config(state=tk.NORMAL)
self.update_time()
def stop_timer(self):
self.timer_running = False
self.start_button.config(state=tk.NORMAL)
self.stop_button.config(state=tk.DISABLED)
def update_time(self):
if self.timer_running:
self.time_left -= timedelta(seconds=1)
self.label.config(text=self.format_time(self.time_left))
if self.time_left == timedelta(seconds=0):
self.timer_running = False
self.master.bell() # 播放提示音
self.master.after(1000, self.update_time)
def format_time(self, time_delta):
minutes, seconds = divmod(time_delta.seconds, 60)
return f'{minutes:02d}:{seconds:02d}'
root = tk.Tk()
timer = CountdownTimer(root)
root.mainloop()
```
运行上面的代码,会弹出一个窗口,窗口中心显示倒计时的时间,左侧是“开始”按钮,右侧是“停止”按钮,点击“开始”按钮,倒计时开始,按钮变为不可用状态,点击“停止”按钮,倒计时暂停,按钮变为不可用状态。当倒计时结束时,会播放提示音。
阅读全文