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

调用self.root.destroy()报错:无法调用tk命令,应用已销毁

问题:CustomTkinter关闭主程序时3D Matplotlib图引发报错

背景

在CustomTkinter主循环中混用TkAgg后端(目前CTk不支持Matplotlib,只能依赖该后端)。

问题

我通过CTkTopLevel窗口展示交互式Matplotlib图形,包括普通折线图和3D三角曲面图。关闭顶层窗口时无异常,但调用destroy()关闭主程序循环时,只有显示并关闭过3D曲面图的情况下会弹出大量错误。

错误信息

bgerror failed to handle background error.
    Original error: invalid command name "2503442563136_checkIfMouseLeft"
    Error in bgerror: can't invoke "tk" command: application has been destroyed
bgerror failed to handle background error.
    Original error: invalid command name "2503735015488check_dpi_scaling"
    Error in bgerror: can't invoke "tk" command: application has been destroyed
bgerror failed to handle background error.
    Original error: invalid command name "2503767702720update"
    Error in bgerror: can't invoke "tk" command: application has been destroyed
bgerror failed to handle background error.
    Original error: invalid command name "2503768283712_click_animation"
    Error in bgerror: can't invoke "tk" command: application has been destroyed

无报错代码(普通折线图)

import customtkinter as ctk
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TkAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg,
    NavigationToolbar2Tk
)

self.topframe = ctk.CTkToplevel(self.root)
figure = Figure(figsize=(6, 4))
figure_canvas = FigureCanvasTkAgg(figure, self.topframe )
NavigationToolbar2Tk(figure_canvas, self.topframe )
ax1 = figure.add_subplot()
ax1.plot(x_data, y_data)
figure_canvas.get_tk_widget().pack()

# if __name__ == "__main__": 以及 root.mainloop 等相关代码

报错代码(3D曲面图)

# 导入部分与上述代码一致
self.topframe = ctk.CTkToplevel(self.root)
figure = Figure(figsize=(8, 8))
figure_canvas = FigureCanvasTkAgg(figure, self.topframe)
NavigationToolbar2Tk(figure_canvas, self.topframe)
ax1 = figure.add_subplot(1, 1, 1, projection='3d')
ax1.plot_trisurf(data_x, data_y, data_z)
figure_canvas.get_tk_widget().pack()

已尝试的解决方法与疑问

  • 尝试在调用self.topframe.destroy()和self.root.destroy()前手动销毁/关闭图形,无效果
  • 尝试用try-except捕获bgerror,未成功

请问这是CustomTkinter与Tkinter混合使用导致的问题,还是关闭交互式3D图特有的问题?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 19:13:19