T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 28 天:Canvas 与计时器:番茄钟

这是「Python 100 天」系列第 28 天的学习笔记:Canvas 与计时器:番茄钟。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

番茄工作法计时器:25 分钟工作 → 5 分钟短休息,每 4 轮一次 20 分钟长休息;界面有背景色、番茄图、倒计时数字、完成标记、Start/Reset 按钮。README 知识点:Canvas 与图片、倒计时机制、动态类型、不同时长切换、勾选标记与重置。

一、Canvas:可以画图的画布

1
2
3
4
5
canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)
tomato = PhotoImage(file="tomato.png")
canvas.create_image(100, 112, image=tomato) # 返回一个 id
text_id = canvas.create_text(100, 130, text="00:00", fill="white")
canvas.itemconfig(text_id, text="01:23") # 通过 id 改内容

要点:

  • create_xxx 返回一个整数 id,之后所有修改都靠这个 id;
  • 改属性用 canvas.itemconfig(id, ...),不是 config;
  • PhotoImage 必须保持引用(存成变量的属性),否则会被垃圾回收,图片变空白;
  • highlightthickness=0 去掉画布默认的焦点边框。

二、定时回调:after

1
2
timer = window.after(1000, count_down, count - 1)   # 1 秒后调用 count_down(count-1)
window.after_cancel(timer) # 取消

after 是 Tkinter 版的 setTimeout:不阻塞界面,到点由事件循环调用。用它做倒计时,比 time.sleep() 好得多——sleep 会让整个窗口卡死。

每次调用返回一个 id,after_cancel(id) 才能取消。不保存 id 就无法停止,这是重置功能的关键。

三、动态类型

Python 变量没有类型,运行时才确定,且可以随时改变:

1
2
x = 10        # int
x = "hello" # 现在变 str,不报错

好处是灵活,坏处是类型错误只能在运行时暴露。count_sec = f"0{count_sec}" 之后 count_sec 从 int 变成了 str,下一轮再 count % 60 就会出错——本项目里它每轮都重新计算,所以侥幸没事。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# ============================================================
# day28/main.py —— 番茄钟(Canvas + after 定时器)
# 作用:25 分钟工作 / 5 分钟短休,每 4 轮工作后 20 分钟长休;
# 界面上倒计时、标题变色、下方用 ✔ 累计完成的番茄数。
# 知识点:Canvas 画布与 create_image/create_text、itemconfig 改画布元素、
# window.after(毫秒, 函数, 参数...) 做非阻塞定时、
# after_cancel 取消定时、global 声明、math.floor、模运算切状态
# 运行方式:cd day28 再 python main.py(同目录要有 tomato.png)
# ============================================================

from tkinter import *
import math

# 配色常量:集中写在这里,改主题只改这几行。
PINK = "#e2979c" # 短休息
RED = "#e7305b" # 长休息
GREEN = "#9bdeac" # 工作
YELLOW = "#f7f5dd" # 背景
FONT_NAME = "Courier"
WORK_MIN = 25 # 工作时长(分钟)
SHORT_BREAK_MIN = 5 # 短休(分钟)
LONG_BREAK_MIN = 20 # 长休(分钟)
# 第几轮(每按一次 Start、每结束一段都 +1)。用 1 开始区分“工作/休息”。
reps = 0
# 保存 after() 返回的定时器 id,reset 时要用它取消正在等待的那一次回调。
timer = None


# 重置:停掉倒计时、清空文字、轮次归零。无参数、无返回值。
def reset_timer():
# after_cancel(id):取消尚未触发的 after 回调。
# 不取消的话,旧倒计时还在后台跑,会和新的叠在一起(两个计时器同时减少)。
window.after_cancel(timer)
# Canvas 上的元素不能用 .config(),要用 canvas.itemconfig(元素id, 属性=值)。
# timer_text 是 create_text 返回的整数 id,不是对象。
canvas.itemconfig(timer_text, text="00:00")
# 标题回到初始状态(字色/背景都要显式写回,config 只改你给的属性)。
title_label.config(text="Timer", font=(FONT_NAME, 50, "bold"), fg=GREEN, bg=YELLOW)
check_label.config(text="")
# 函数内部要给全局变量赋值,必须先 global 声明,否则会新建一个局部变量。
global reps
reps = 0


# 开始/进入下一段:根据 reps 决定这段是工作、短休还是长休。无参数、无返回值。
def start_timer():
global reps
reps += 1

# 分钟换算成秒,after 的单位是毫秒,等下再 ×1000。
work_sec = WORK_MIN * 60
short_break_sec = SHORT_BREAK_MIN * 60
long_break_sec = LONG_BREAK_MIN * 60

# 轮次规律:1 工作、2 短休、3 工作、4 短休…8 长休(即每 4 个番茄一次长休)。
# 先判 % 8 == 0,再判 % 2 == 0:顺序不能反,因为 8 也是偶数,
# 反过来的话长休永远进不去。
if reps % 8 == 0:
title_label.config(text="Break", fg=RED)
count_down(long_break_sec)
elif reps % 2 == 0:
title_label.config(text="Break", fg=PINK)
count_down(short_break_sec)
else:
title_label.config(text="Work", fg=GREEN)
count_down(work_sec)


# 倒计时。参数 count:还剩多少秒(int)。
def count_down(count):
# math.floor(浮点):向下取整。count/60 在 Python3 是浮点,所以要 floor。
# 整除写法 count // 60 更直接。
count_min = math.floor(count / 60)
# % 取余得到不足一分钟的秒数。
count_sec = count % 60
# 秒数补零:9 → "09",否则会显示 4:9 这种怪格式。
if count_sec < 10:
count_sec = f"0{count_sec}"
# 改画布文字(不是 Label,所以用 itemconfig)。
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
global timer
# after(毫秒, 回调, 传给回调的参数...):1000 毫秒后再调一次 count_down(count-1)。
# 它**不阻塞**,立刻返回一个 id,界面照常响应 —— 这就是 Tkinter 里做循环的方式。
# 返回值存进全局 timer,reset 时才能取消。
timer = window.after(1000, count_down, count - 1)
else:
# 归零:立刻开始下一段(工作↔休息自动切换)。
# 注意原代码没有“停止”按钮逻辑,点 Start 后会一直自动循环下去。
start_timer()
# 下方打勾:每完成 2 个 reps(一个工作段)一个 ✔。
# 这里的 reps 已经是 start_timer() 加过 1 之后的值。
marks = ""
for _ in range(math.floor(reps / 2)):
marks += "✔"
check_label.config(text=marks)


window = Tk()
window.title("Pomodoro")
# bg=YELLOW:窗口底色。子控件不继承,Label/Canvas 都要各自设 bg,否则是灰色块。
window.config(padx=100, pady=50, bg=YELLOW)

# Canvas(width, height, bg):画布,可以在上面画图/写字。
# highlightthickness=0:去掉画布默认的 1 像素焦点边框(很丑)。
canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)
# PhotoImage(file=...):读图片。注意 Tk 8.6 只原生支持 png/gif,
# 不支持 jpg;而且必须保持引用(存进变量),否则会被垃圾回收、图片变空白。
tomato_png = PhotoImage(file="tomato.png")
# create_image(x, y, image=...):在画布坐标 (x, y) 贴图,返回元素 id。
# 坐标是“图片中心点”,200×224 的画布放 (100, 112) 正好居中。
canvas.create_image(100, 112, image=tomato_png)
# create_text(x, y, text=, fill=, font=):在画布上写字,返回元素 id(后面 itemconfig 用)。
timer_text = canvas.create_text(100, 130, text="00:00", fill="white", font=(FONT_NAME, 35, "bold"))
canvas.grid(column=1, row=1)

title_label = Label(text="Timer", font=(FONT_NAME, 50, "bold"), fg=GREEN, bg=YELLOW)
title_label.grid(column=1, row=0)

# 只给 font/fg/bg,不给 text —— 初始是空字符串,完成一段后才有 ✔。
check_label = Label(font=(FONT_NAME, 20, "bold"), fg=GREEN, bg=YELLOW)
check_label.grid(column=1, row=3)

# command 传函数对象(不带括号),点击时才调用。
start_button = Button(text="Start", command=start_timer)
start_button.grid(column=0, row=2)

reset_button = Button(text="Reset", command=reset_timer)
reset_button.grid(column=2, row=2)


window.mainloop()

代码走读

  1. 常量区:四个颜色(十六进制)、字体名、三档时长。颜色和时长集中定义,改主题只改这里。
  2. reps = 0、timer = None:两个模块级状态。reps 记录第几轮,timer 存 after 的 id。
  3. start_timer():reps += 1 后按 reps % 8、reps % 2 决定是长休息、短休息还是工作,改标题颜色并启动倒计时。
  4. count_down(count):
  • count_min = math.floor(count/60)、count_sec = count % 60;
  • 秒数小于 10 补 0(5 → "05");
  • canvas.itemconfig(timer_text, text=...) 更新显示;
  • count > 0 就 after(1000, count_down, count-1) 递归调度;
  • 到 0 则 start_timer() 进入下一阶段,并按 reps/2 画勾。
  1. reset_timer():取消定时器、数字归零、标题复原、清空勾、reps = 0。
  2. 界面:Canvas 放番茄图和文字,标题 Label、勾 Label、两个 Button,全部 grid 到 3 列。

这里有一处需要 global

1
2
3
4
def count_down(count):
...
global timer
timer = window.after(...)

因为函数里给 timer 赋值,不加 global 就会创建一个局部变量,外层的 timer 仍是 None,reset_timer() 里的 after_cancel(None) 就取消不了——重置后计时器还在跑(会出现两个倒计时同时刷新)。

运行效果

黄色背景、番茄图、白色数字每秒递减;工作 25 分钟后自动切到 5 分钟休息,标题变粉色;第 8 轮是 20 分钟长休息。

易错点

  1. PhotoImage 只存在局部变量里:图片被回收,画布空白。
  2. 用 time.sleep 做倒计时:窗口无响应。
  3. 忘 after_cancel:点 Reset 后旧计时器继续跑。
  4. count_sec 补零后类型变字符串:别拿它再参与算术。
  5. reps 不加 global:每次调用都从 0 开始,永远进不了休息阶段。

动手改

  • 加"暂停/继续":保存剩余秒数,after_cancel 后从剩余值恢复。
  • 把时长改成可配置(Scale 或 Entry)。
  • 长休息结束后弹窗提醒。

源文件逐个讲解

3 个文件:

文件 规模 职责
main.py85 行番茄钟:三色主题、倒计时、自动换阶段
tomato.png10.8KB番茄图(Canvas 背景)
README.md10 行说明页

tomato.png

一张带透明背景的 PNG,贴在 Canvas 上作为「番茄钟」的视觉主体。PNG 的透明通道在这里很重要——jpg 会带白底方块。

main.py(85 行)

结构:8 个常量 → 3 个函数 → 一堆控件。这是全书第一个「状态机」程序。

1
2
3
4
5
6
7
8
9
10
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
reps = 0
timer = None

前四个是颜色十六进制,第五个是字体名——把它们抽成常量,是为了「一改全改」(比如换整套配色只改 4 行)。

reps = 0 和 timer = None 是全局状态:

  • reps:第几轮(1 工作、2 短休、3 工作…8 长休);
  • timer:after() 返回的定时器 ID,取消定时必须靠它。
1
2
3
4
5
6
7
def reset_timer():
window.after_cancel(timer)
canvas.itemconfig(timer_text, text="00:00")
title_label.config(text="Timer", font=(FONT_NAME, 50, "bold"), fg=GREEN, bg=YELLOW)
check_label.config(text="")
global reps
reps = 0

after_cancel(timer) 是这一天的关键 API:window.after(1000, fn) 会返回一个 ID,只有拿着 ID 才能取消。不取消的话,重置后旧的倒计时还在跑,会出现「两个倒计时同时跳」。

canvas.itemconfig(timer_text, ...):Canvas 上的文字不是控件,是「item」,要用 itemconfig 改,不能用 .config()。timer_text 是 create_text 的返回值(item ID)。

global reps 放在函数中间:Python 允许,但规范写法是放函数第一行。放在中间容易看漏。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def start_timer():
global reps
reps += 1

work_sec = WORK_MIN * 60
short_break_sec = SHORT_BREAK_MIN * 60
long_break_sec = LONG_BREAK_MIN * 60

if reps % 8 == 0:
title_label.config(text="Break", fg=RED)
count_down(long_break_sec)
elif reps % 2 == 0:
title_label.config(text="Break", fg=PINK)
count_down(short_break_sec)
else:
title_label.config(text="Work", fg=GREEN)
count_down(work_sec)

这就是番茄工作法的节奏表:

reps 阶段 时长 颜色
1,3,5,7工作25 分绿
2,4,6短休5 分粉
8长休20 分红

判 reps % 8 == 0 必须在 reps % 2 == 0 之前——8 也是偶数,顺序反了长休永远轮不到。这是 elif 顺序的又一个考点(和 Day 13 的 FizzBuzz 一模一样)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def count_down(count):
count_min = math.floor(count / 60)
count_sec = count % 60
if count_sec < 10:
count_sec = f"0{count_sec}"
canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
if count > 0:
global timer
timer = window.after(1000, count_down, count - 1)
else:
start_timer()
marks = ""
for _ in range(math.floor(reps/2)):
marks += "✔"
check_label.config(text=marks)

这个函数是「用回调实现循环」的范本:

  • 不是 while 循环,而是「设一个 1 秒后的回调,回调里再设下一个」;
  • window.after(1000, count_down, count - 1):1000 毫秒后调用 count_down(count-1)——第三个及之后的参数会原样传给回调。

为什么不用 time.sleep(1)? 因为 Tkinter 是单线程的,sleep 会冻住整个界面(按钮点不动、窗口拖不动)。after 把控制权还给事件循环,界面始终可响应。

count_sec 补零:if count_sec < 10: count_sec = f"0{count_sec}"。这行之后 count_sec 从 int 变成了 str——类型悄悄变了,后面如果还要算术就会崩(这里没有,所以安全)。

count > 0 才继续,等于 0 时进 else:先 start_timer() 开下一阶段,再画 ✔。

math.floor(reps/2) 决定打几个勾:reps=2(刚完成第一轮工作)打 1 个,reps=4 打 2 个……

marks += "✔" 在循环里拼字符串——轮数少无所谓,多了就是 O(n²)。

注意 reps/2 用的是浮点除法再 floor,等价于 reps // 2。

控件部分

1
2
3
4
5
canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)
tomato_png = PhotoImage(file="tomato.png")
canvas.create_image(100, 112, image=tomato_png)
timer_text = canvas.create_text(100, 130, text="00:00", fill="white", font=(FONT_NAME, 35, "bold"))
canvas.grid(column=1, row=1)

highlightthickness=0 去掉 Canvas 默认的焦点边框(不然番茄图周围有一圈虚线)。

create_image(100, 112, ...) 把图贴在 Canvas 中心(200×224 的一半)。create_text(100, 130, ...) 把倒计时数字叠在番茄下半部分。

tomato_png 必须存成变量:PhotoImage 对象如果只在局部变量里,会被垃圾回收,图就消失了。这是 Tkinter 最经典的坑之一。

1
2
3
4
5
6
7
8
title_label = Label(text="Timer", font=(FONT_NAME, 50, "bold"), fg=GREEN, bg=YELLOW)
title_label.grid(column=1, row=0)
check_label = Label(font=(FONT_NAME, 20, "bold"), fg=GREEN, bg=YELLOW)
check_label.grid(column=1, row=3)
start_button = Button(text="Start", command=start_timer)
start_button.grid(column=0, row=2)
reset_button = Button(text="Reset", command=reset_timer)
reset_button.grid(column=2, row=2)

布局是 3 列 × 4 行:

col 0 col 1 col 2
row 0标题
row 1Canvas
row 2StartReset
row 3✔✔✔

mainloop() 之前的代码全部按顺序执行,window.after 的回调要等 mainloop 启动后才会被调度。

这份代码的问题

  1. reset_timer 之后 reps 归零,但 count_down 的旧链可能还在跑:after_cancel(timer) 只取消了最后一个 ID。如果 Reset 时正好在一次回调执行的瞬间,可能漏掉一次。
  2. timer 是全局变量,count_down 里每轮覆盖:只保留最后一个 ID,历史 ID 不可取消。
  3. global reps 写在函数中间,不符合惯例。
  4. count_sec 类型从 int 变 str,是隐患。
  5. marks += "✔" 的 O(n²)。
  6. tomato.png 用相对路径:不在 day28/ 目录下运行会 TclError: couldn't open "tomato.png"。

README.md(10 行)

标题 Day 28 - Tkinter, Dynamic Typing and the Pomodoro GUI Application,知识点:How to work with the Canvas Widget and Add Images to Tkinter、Add Overlap to the Canvas、Challenge - Complete the Application's User Interface、Implement the Countdown、Dynamic Typing。

Add Overlap 就是「图 + 文字叠在同一个 Canvas 上」,Dynamic Typing 正是 count_sec 从 int 变 str 那个现象——这一天刻意用它来演示「Python 变量没有固定类型」。

三个文件的关系

1
2
3
4
tomato.png ──PhotoImage──▶ canvas.create_image
↑
count_down 用 itemconfig 改上面的字
main.py 里三个函数 + 四个控件,全部平铺在模块级

没有任何类——这一天还是「过程式 + 全局变量」。Day 34 会用类把 GUI 重写一遍。

微信收款码 微信
支付宝收款码 支付宝
评论