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

嵌入Tkinter的Matplotlib窗口关闭后无法退出主循环问题

解决Tkinter窗口关闭后程序仍运行的问题

问题根源是Matplotlib与Tkinter结合时,关闭窗口后Matplotlib的后台资源未被彻底清理,导致进程残留。以下是具体解决方法:

关键修改点

  • 显式指定Matplotlib使用TkAgg后端,避免默认后台遗留进程
  • 给Tk窗口绑定关闭事件,同步清理Matplotlib资源并终止程序

修改后的可运行代码

# 先指定Matplotlib后端为TkAgg,确保与Tkinter兼容
import matplotlib
matplotlib.use('TkAgg')

import matplotlib.pyplot as plt
from tkinter import Tk, Frame
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

Dates = ["a","b","c","d"]
Numbers = [1,4,2,6]

def test():
    fig, ax = plt.subplots(figsize=(10,7))
    ax.plot(Dates, Numbers, linestyle='-', color='gray', alpha=0.5)
    
    root = Tk()
    root.title("Test")
    
    # 定义窗口关闭时的处理逻辑
    def on_closing():
        plt.close(fig)  # 释放Matplotlib的绘图资源
        root.destroy()  # 销毁Tkinter窗口
        exit()  # 彻底终止程序
    
    # 绑定窗口关闭事件到自定义处理函数
    root.protocol("WM_DELETE_WINDOW", on_closing)
    
    frame = Frame(root)
    frame.pack(fill='both', expand=True)
    
    canvas = FigureCanvasTkAgg(fig, master=frame)
    canvas.draw()
    canvas.get_tk_widget().pack(fill='both', expand=True)
    
    def f_test():
        print("HI")
    f_test()
    
    root.mainloop()

test()

额外优化说明

  • 移除了代码中重复的from tkinter import Tk导入,减少冗余
  • 若无需立即终止整个程序,可仅保留plt.close(fig)和root.destroy(),但exit()能更彻底地解决进程残留问题

内容的提问来源于stack exchange,提问作者Leandro Zárate

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:17:05