嵌入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
相关产品推荐
相关产品推荐

