matplotlib 挂接到 save_figure 按钮事件

matplotlib hooking in to save_figure button events

有谁知道如何从 matplotlib 图形中获取 'save figure' 按钮事件?

我需要事件来在按下此按钮时调用我的一些功能。

import matplotlib.pyplot as plt
from matplotlib.backend_bases import NavigationToolbar2

save_figure = NavigationToolbar2.save_figure

def new_save(self, *args, **kwargs):
  print( 'save_event')
  # save_figure(self, *args, **kwargs)

NavigationToolbar2.save_figure = new_save


fig = plt.figure()
plt.text(0.35, 0.5, 'Hello world!', dict(size=30))
plt.show()

但是如果我按下 save figure 它不会调用我的函数 new_save

matplotlib.backend_bases.NavigationToolbar2 does not implement a save_figure method. This method is implemented in each of the backends specifically. E.g. for the Qt5Agg backend this is here。因此,您需要对正在使用的实际后端的相应方法进行猴子修补。 对于 Qt5Agg 后端,这可能看起来像这样:

import matplotlib
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5 import NavigationToolbar2QT

save_figure = NavigationToolbar2QT.save_figure

def new_save(self, *args, **kwargs):
  print('save_event')
  save_figure(self, *args, **kwargs)

NavigationToolbar2QT.save_figure = new_save

fig = plt.figure()
plt.text(0.35, 0.5, 'Hello world!', dict(size=30))
plt.show()