当前位置 博文首页 > matplotlib更改窗口图标的方法示例

    matplotlib更改窗口图标的方法示例

    作者:mighty13 时间:2021-07-29 18:43

    matplotlib窗口图标默认是matplotlib的标志,如果想修改怎么改呢?

    由于我选择的matplotlib后端是PyQT5,直接查看matplotlib.backends.backend_qt5模块源码。

    原理

    查看源码可知,窗口图标功能定义在FigureManagerQT类中,设置的默认图标是mpl-data\images\matplotlib.svg。
    FigureManagerQT的父类是FigureManagerBase,其功能是作为容器隔离matplotlib图像和后端实现的窗口,并与窗口进行交互,它会自动适配matplotlib选用的后端。
    这样只用找到当前图像中FigureManagerQT类的实例(即当前图像的图像管理器)后调用setWindowIcon方法即可完成窗口图标的更改。
    获取当前图像的图像管理器有两种写法,因此,更改窗口图标的实现有两种。
    根据matplotlib.pyplot.get_current_fig_manager()函数源码可知这两种方法是等价的。

    实现代码

    import matplotlib.pyplot as plt
    from PyQt5 import QtGui
    
    plt.plot([1,2])
    # 构建图标
    PATH_TO_ICON = r"c:\quit.png"
    new_icon = QtGui.QIcon(PATH_TO_ICON)
    # 方法一:使用figure.canvas.manager获取当前图像的`FigureManagerQT`类实例
    fig =plt.gcf()
    fig.canvas.manager.window.setWindowIcon(QtGui.QIcon(new_icon))
    
    # 方法二:使用plt.get_current_fig_manager()获取当前图像的`FigureManagerQT`类实例
    plt.get_current_fig_manager().window.setWindowIcon(new_icon)
    plt.show()
    

    matplotlib源码

    class FigureManagerQT(FigureManagerBase):
      """
      Attributes
      ----------
      canvas : `FigureCanvas`
        The FigureCanvas instance
      num : int or str
        The Figure number
      toolbar : qt.QToolBar
        The qt.QToolBar
      window : qt.QMainWindow
        The qt.QMainWindow
      """
    
      def __init__(self, canvas, num):
        FigureManagerBase.__init__(self, canvas, num)
        self.window = MainWindow()
        self.window.closing.connect(canvas.close_event)
        self.window.closing.connect(self._widgetclosed)
    
        self.window.setWindowTitle("Figure %d" % num)
        image = str(cbook._get_data_path('images/matplotlib.svg'))
        self.window.setWindowIcon(QtGui.QIcon(image))
    
    def get_current_fig_manager():
      return gcf().canvas.manager
    jsjbwy