使用 tk 后端时如何关闭图形 [英] how to close a Figure when using tk backend

查看:88
本文介绍了使用 tk 后端时如何关闭图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我节省了很多地块.

So I am saving a lot of plots.

旧代码:

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.

other parts of my code are using Tkinter so I can not use 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后端时如何关闭图形?

How can I close a Figure when using tk backend?

推荐答案

FigureCanvasTkAgg 没有 destroy 方法.所以我尝试了:

FigureCanvasTkAgg does not have a destroy method. So I tried:

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__绑定到它所在的顶层,因此:

but no luck, turns out FigureCanvasTkAgg.__init__ binds to the toplevel it is placed in, so:

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()

似乎为我工作.

这篇关于使用 tk 后端时如何关闭图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆