使用 tk 后端时如何关闭图形

how to close a Figure when using tk backend

所以我节省了很多地块。

旧代码:

import matplotlib.pyplot as plt


for args in lots_of_things_to_make:
    fig = plt.figure()
    do_the_fancy_graphing(fig, *args)
    fig.savefig(out_path)
    plt.close()

我的代码的其他部分正在使用 Tkinter,所以我不能使用 pyplot。

新代码:

import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure


for args in lots_of_things_to_make:
    fig = Figure()
    do_the_fancy_graphing(fig, *args)
    canvas = FigureCanvasTkAgg(fig, master=root)
    fig.savefig(out_path)

这导致 _tkinter.TclError: not enough free memory for image buffer

如何在使用 tk 后端时关闭图?

FigureCanvasTkAgg 没有销毁方法。所以我尝试了:

for args in lots_of_things_to_make:
    fig = Figure()
    frame = Frame(root)
    do_the_fancy_graphing(fig, *args)
    canvas = FigureCanvasTkAgg(fig, master=frame)
    fig.savefig(out_path)
    frame.destroy()

但运气不好,结果是 FigureCanvasTkAgg.__init__ 绑定到它所在的顶层,所以:

for args in lots_of_things_to_make:
    fig = Figure()
    top = Toplevel(root)
    do_the_fancy_graphing(fig, *args)
    canvas = FigureCanvasTkAgg(fig, master=top)
    fig.savefig(out_path)
    top.destroy()

似乎对我有用。