帮我用tKinter编写一个倒计时定时器工具,要能设置时长
时间: 2024-10-18 11:22:17 浏览: 39
在Python中,我们可以使用Tkinter库创建一个简单的倒计时定时器工具。首先确保已安装了Tkinter模块。以下是一个基础的倒计时计时器示例,用户可以输入时长并开始倒计时:
```python
import tkinter as tk
from datetime import datetime, timedelta
def countdown(start_time, duration):
while start_time > datetime.now():
mins, secs = divmod((start_time - datetime.now()).total_seconds(), 60)
mins = round(mins)
secs = round(secs)
count_label.config(text=f"Time Left: {mins}m {secs}s")
root.update_idletasks()
time.sleep(1)
count_label.config(text="Countdown Finished!")
def set_timer():
try:
hours = int(hours_entry.get())
minutes = int(minutes_entry.get())
seconds = int(seconds_entry.get())
total_seconds = hours * 3600 + minutes * 60 + seconds
end_time = datetime.now() + timedelta(seconds=total_seconds)
start_time = end_time
if start_time <= datetime.now():
tk.messagebox.showerror("Error", "Invalid timer settings.")
else:
countdown_button.config(state=tk.DISABLED)
countdown_thread = threading.Thread(target=countdown, args=(start_time, total_seconds))
countdown_thread.start()
except ValueError:
tk.messagebox.showerror("Error", "Please enter valid numbers for hours, minutes, and seconds.")
root = tk.Tk()
root.title("Timer")
hours_label = tk.Label(root, text="Hours:")
hours_label.grid(row=0, column=0)
hours_entry = tk.Entry(root)
hours_entry.grid(row=0, column=1)
minutes_label = tk.Label(root, text="Minutes:")
minutes_label.grid(row=1, column=0)
minutes_entry = tk.Entry(root)
minutes_entry.grid(row=1, column=1)
seconds_label = tk.Label(root, text="Seconds:")
seconds_label.grid(row=2, column=0)
seconds_entry = tk.Entry(root)
seconds_entry.grid(row=2, column=1)
count_label = tk.Label(root, text="")
count_label.grid(row=3, columnspan=2)
countdown_button = tk.Button(root, text="Start Countdown", command=set_timer)
countdown_button.grid(row=4, columnspan=2)
root.mainloop()
```
在这个脚本中,用户通过输入小时、分钟和秒来设置倒计时,然后点击"Start Countdown"按钮触发倒计时。
阅读全文