【问题标题】:matplotlib hooking in to save_figure button eventsmatplotlib 连接到 save_figure 按钮事件
【发布时间】:2019-07-23 05:20:34
【问题描述】:

有人知道如何从 matplotlib 图形中获取“保存图形”按钮事件吗?

当按下这个按钮时,我需要事件来调用我的一些函数。

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 events button backend


    【解决方案1】:

    matplotlib.backend_bases.NavigationToolbar2does not implementsave_figure 方法。该方法具体在每个后端实现。例如。对于 Qt5Agg 后端,这是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()
    

    【讨论】:

      猜你喜欢
      • 2017-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-05
      • 2016-01-11
      • 2022-11-24
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多