【Python】tkinter实现番茄钟

查看 68|回复 7
作者:moduwusuowei   
好久没看论坛了,今天看到一个小伙伴分享了一个番茄钟的工具,并没有提供源码,来到这个区域的人不仅对工具感兴趣,同时保留着对源码的热爱;
一开始是真不知道什么是番茄钟,搜了一下,差不多就是倒计时用的,类似围棋对决的时候有时间限制,那是两个倒计时钟,基于这个场景用python代码实现;
整体来说这段代码难度为3颗星,就是简单逻辑梳理清楚就可以动手写代码了,太复杂的计算与逻辑并没有在这个工具上使用;
提供了源码,没有额外的第三方库,可以在本地直接运行,新手小白也能搞定;
import tkinter as tk
from tkinter import messagebox
import time
class TomatoClock:
    def __init__(self, root):
        self.root = root
        self.debug = True
        self.root.title("番茄钟_moduwusuowei")
        self.root.geometry("250x100")
        self.time_entry = tk.Entry(root, width=30, font=('Helvetica', 22))
        self.time_entry.pack(pady=5, padx=5)
        self.start_button = tk.Button(root, text="开始", command=self.start_countdown, font=('Helvetica', 22))
        self.start_button.pack(pady=5, padx=5)
        self.countdown_label = tk.Label(root, text="", font=('Helvetica', 28))
        self.countdown_label.pack(pady=25)
        self.is_running = False
    def start_countdown(self):
        if self.is_running:
            return
        self.is_running = True
        self.time_entry.pack_forget()
        self.start_button.pack_forget()
        try:
            if self.debug:
                total_seconds = int(self.time_entry.get())
            else:
                total_seconds = int(self.time_entry.get()) * 60
        except ValueError:
            messagebox.showerror("错误", "请输入有效的分钟数")
            self.reset_clock()
            return
        while total_seconds > 0:
            print(f"Remaining: {total_seconds} seconds")
            if self.debug:
                mins = 0
                secs = total_seconds
            else:
                mins, secs = divmod(total_seconds, 60)
            text = f"{mins:02d}:{secs:02d}"
            print(f"{text=}")
            self.countdown_label.pack()
            self.countdown_label.config(text=text)
            self.root.update()
            time.sleep(1)
            total_seconds -= 1
        messagebox.showinfo("时间到!", "您的番茄钟时间已经结束。")
        self.reset_clock()
    def reset_clock(self):
        self.is_running = False
        self.countdown_label.pack_forget()
        self.countdown_label.config(text="")
        self.time_entry.delete(0, tk.END)
        self.time_entry.pack(pady=5, padx=5)
        self.start_button.pack(pady=5, padx=5)
if __name__ == "__main__":
    root = tk.Tk()
    app = TomatoClock(root)
    root.mainloop()
运行效果也比较简洁:


fanqiezhong.gif (10.86 KB, 下载次数: 0)
下载附件
番茄钟
2025-6-4 14:23 上传

番茄, 源码

sktao   

这个上面显示时间,下面再有闹钟就更好了,然后闹钟增加提醒事件 可以选择每天都这样,
CapCCC   

感谢分享
233277327   

感谢楼主分享!
yilong88888   

怎么用呢  ?
抱薪风雪雾   

多谢,分享好玩好用的小软
mytomsummer   

感谢分享有趣的小工具
yiluoen0502   

感谢分享
您需要登录后才可以回帖 登录 | 立即注册

返回顶部