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

(编辑:jimmy 日期: 2024/9/22 浏览:2)

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

一句话新闻

Windows上运行安卓你用过了吗
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。