如何检测轴属于已在 matplotlib 中关闭的窗口

Ste*_*eve 2 python matplotlib

在 matplotlib 中,我在轴上保留一个参考。如果包含轴的窗口已关闭,我想打开一个新图形。这个想法是继续在图形上添加绘图,直到它关闭,然后我打开一个新图形。请注意,新图的创建是由另一个图中的事件触发的。

如果它可以帮助您理解我正在尝试做的事情,这里是课程:

class DetailedPlot(object):
    def __init__(self, figure):
        self.origin_figure = figure

        self.axis = None
        self.print_figure = None

        self.origin_figure.canvas.mpl_connect('button_press_event', self)


    def __call__(self, event):
        if event.xdata is None or event.ydata is None:
            return
        r = round(event.xdata - 0.025, 1)
        l = round(event.ydata - 0.025, 1)
        if self.axis is None or self.axis.belongs_to_a_closed_window():
            self.print_figure = plt.figure()
            self.axis = self.print_figure.add_subplot(111)
        plotting_fcn(self.axis, r, l)
Run Code Online (Sandbox Code Playgroud)

我的目标是找到一个函数,例如belongs_to_a_closed_window

Joe*_*ton 5

为什么不直接将回调连接到"close_event"?您可以ax.has_been_closed向轴对象或您的类本身添加一个标志。(可能有比“has_been_closed”标志更简洁的解决方案,具体取决于您在做什么......回调函数可以是任何东西。)

import matplotlib.pyplot as plt

def on_close(event):
    event.canvas.figure.axes[0].has_been_closed = True
    print 'Closed Figure'

fig = plt.figure()
ax = fig.add_subplot(111)
ax.has_been_closed = False
ax.plot(range(10))

fig.canvas.mpl_connect('close_event', on_close)

plt.show()

print ax.has_been_closed
Run Code Online (Sandbox Code Playgroud)

编辑:(扩展我在下面的评论)如果 OSX 后端没有正确实现关闭事件,您还可以执行以下操作:

import matplotlib.pyplot as plt

def has_been_closed(ax):
    fig = ax.figure.canvas.manager
    active_fig_managers = plt._pylab_helpers.Gcf.figs.values()
    return fig not in active_fig_managers

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))

print has_been_closed(ax)

plt.show()

print has_been_closed(ax)
Run Code Online (Sandbox Code Playgroud)