📅  最后修改于: 2023-12-03 14:38:48.038000             🧑  作者: Mango
在Python中实现一个10分钟计时器并不困难。我们可以使用datetime、time和tkinter模块。下面是一个可以实现10分钟计时的程序,包含开始、停止和重置按钮。
import datetime
import time
import tkinter as tk
class Timer:
def __init__(self, master):
self.master = master
self.master.title("10 Minute Timer")
self.timer_running = False
self.start_time = None
self.countdown_seconds = None
self.timer_text = tk.StringVar()
self.timer_text.set("10:00")
timer_label = tk.Label(self.master, textvariable=self.timer_text, font=("Helvetica", 48))
timer_label.pack(padx=50, pady=20)
start_button = tk.Button(self.master, text="Start", command=self.start_timer)
start_button.pack(side="left", padx=(50, 10), pady=10)
stop_button = tk.Button(self.master, text="Stop", command=self.stop_timer)
stop_button.pack(side="left", padx=(10, 50), pady=10)
reset_button = tk.Button(self.master, text="Reset", command=self.reset_timer)
reset_button.pack(side="left", pady=10)
def start_timer(self):
if not self.timer_running:
self.timer_running = True
self.start_time = datetime.datetime.now()
self.countdown_seconds = 600
self.update_timer()
def stop_timer(self):
if self.timer_running:
self.timer_running = False
def reset_timer(self):
if self.timer_running:
self.stop_timer()
self.timer_text.set("10:00")
def update_timer(self):
if self.timer_running:
time_elapsed = (datetime.datetime.now() - self.start_time).seconds
time_left = self.countdown_seconds - time_elapsed
if time_left <= 0:
self.timer_text.set("00:00")
self.timer_running = False
else:
minutes, seconds = divmod(time_left, 60)
self.timer_text.set("{:02d}:{:02d}".format(minutes, seconds))
self.master.after(1000, self.update_timer)
使用tkinter模块创建简单的GUI界面,包含一个显示计时器剩余时间的Label和三个按钮:开始、停止和重置。
这段代码实现了一个简单的10分钟计时器,用户可以手动启动和停止。