python - Detect which figure was closed with Matplotlib -
im using matplotlib embedded in gui application using qt4 backend.
i need store list of figures user plots , keeps open ie multiple figures able plotted separately different clicks of plot button.
however when user closes figure need remove list of figures.
how tell figure closed?
i using event handler detect figure has been closed cannot tell one.
here trivial example code:
from __future__ import print_function import matplotlib.pyplot plt import numpy np figs = [] fignum = len(figs) def handle_close(evt): evt.canvas.figure.axes[0].has_been_closed = true print ('closed figure') fig = plt.figure() figs.append(fig) ax = figs[fignum].add_subplot(1, 1, 1) ax.has_been_closed = false # fig2 = plt.figure() # ax2 = fig2.add_axes([0.15, 0.1, 0.7, 0.3]) t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) line, = ax.plot(t, s, color='blue', lw=2) # fig2 = plt.figure() # figs.append(fig2) # fig2.canvas.mpl_connect('close_event', handle_close) fig.canvas.mpl_connect('close_event', handle_close) plt.show() print (ax.has_been_closed)
the evt
passed handler has member canvas
, in turn has member figure
, of course figure event refers to.
so if want remove figure list, do
figs.remove(evt.canvas.figure)
if want figure number, access
evt.canvas.figure.number
and name from
evt.canvas.figure._label
however, leading _
means shouldn't rely on that.
Comments
Post a Comment