You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Canvas时触发‘Exception in Tkinter callback’异常的问题

问题:Tkinter Pomodoro计时器点击Start按钮后崩溃

尝试在Tkinter Canvas上实现更新的计时器,点击Start按钮后程序崩溃,完整代码如下:

from tkinter import *
import math
# ---------------------------- CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20

# ---------------------------- TIMER RESET ------------------------------- # 

# ---------------------------- TIMER MECHANISM ------------------------------- # 
def start_timer():
    count_down(5*60)

# ---------------------------- COUNTDOWN MECHANISM ------------------------------- # 
def count_down(count):
    count_min = math.floor(count/60)
    count_sec = count % 60
    canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
    if count > 0:
        window.after(1000, count_down, count-1)

# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Pomodoro")
window.config(padx=100, pady=50, bg=YELLOW)

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

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

start_button = Button(text="Start",font=("Arial",12),highlightthickness=0,command=start_timer)
start_button.grid(column=0,row=2)
reset_button = Button(text="Reset",font=("Arial",12),highlightthickness=0)
reset_button.grid(column=2, row=2)

checkmark = Label(text="✔️",bg=YELLOW,font=(10),fg=GREEN)
checkmark.grid(column=1,row=3)

window.mainloop()

崩溃时的完整报错信息:

Exception in Tkinter callback                                                                                                               
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.752.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 1948, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "f:\Programming\python\255 pomodoro-start\main.py", line 17, in start_timer
    count_down(5*60)
  File "f:\Programming\python\255 pomodoro-start\main.py", line 23, in count_down
    canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.752.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 2959, in itemconfigure
    return self._configure(('itemconfigure', tagOrId), cnf, kw)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.752.0_x64__qbz5n2kfra8p0\Lib\tkinter\__init__.py", line 1692, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid boolean operator in tag search expression

问题原因

变量名冲突导致:

  • 首先用timer_text存储了Canvas创建的文本项ID(canvas.create_text返回的整数ID)
  • 随后又将顶部的Label控件赋值给同一个timer_text变量,覆盖了之前的Canvas文本项ID
  • 当count_down函数调用canvas.itemconfig(timer_text, ...)时,传入的是Label对象而非Canvas文本项ID,Tkinter无法识别这个对象,因此抛出错误

解决方案

修改顶部Label控件的变量名,避免和Canvas文本项的变量名重复,比如改为timer_label。修改后的完整代码如下:

from tkinter import *
import math
# ---------------------------- CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20

# ---------------------------- TIMER RESET ------------------------------- # 

# ---------------------------- TIMER MECHANISM ------------------------------- # 
def start_timer():
    count_down(5*60)

# ---------------------------- COUNTDOWN MECHANISM ------------------------------- # 
def count_down(count):
    count_min = math.floor(count/60)
    count_sec = count % 60
    # 优化:秒数小于10时显示为两位(比如05而不是5)
    if count_sec < 10:
        count_sec = f"0{count_sec}"
    canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
    if count > 0:
        window.after(1000, count_down, count-1)

# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Pomodoro")
window.config(padx=100, pady=50, bg=YELLOW)

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

# 修改变量名为timer_label,避免冲突
timer_label = Label(text="Timer", font=(FONT_NAME,50,"bold"),fg=GREEN,bg=YELLOW)
timer_label.grid(column=1,row=0)

start_button = Button(text="Start",font=("Arial",12),highlightthickness=0,command=start_timer)
start_button.grid(column=0,row=2)
reset_button = Button(text="Reset",font=("Arial",12),highlightthickness=0)
reset_button.grid(column=2, row=2)

checkmark = Label(text="✔️",bg=YELLOW,font=(10),fg=GREEN)
checkmark.grid(column=1,row=3)

window.mainloop()

额外优化:添加了秒数补零逻辑,让显示格式更统一(比如5:05而不是5:5)

内容的提问来源于stack exchange,提问作者Mayur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 17:18:08