检测Matplotlib关闭了哪个数字

时间:2015-06-26 09:16:15

标签: python matplotlib

我使用qt4后端在GUI应用程序中嵌入了matplotlib。

我需要存储用户绘制并保持打开的图形列表,即可以使用不同的绘图按钮单独绘制多个图形。

然而,当用户关闭图形时,我需要将其从图形列表中删除。

如何判断哪个数字已关闭?

我正在使用事件处理程序来检测数字已经关闭,但我无法分辨哪一个。

以下是一些简单的示例代码:

from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as 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)

1 个答案:

答案 0 :(得分:0)

The evt that is passed to your handler has a member canvas, which in turn has a member figure, which of course is the figure the event refers to.

So if you want to remove that figure from your list, you would do

figs.remove(evt.canvas.figure)

If you want to get the figure number, you access

evt.canvas.figure.number

and you could get the name from

evt.canvas.figure._label

However, the leading _ probably means you shouldn't rely on that.