从一文可知matplotlib内置实现了多个工具项的实现,而默认工具栏中的工具项只是其中的一部分,有没有方法直接管理工具栏,添加、删除内置工具项?

matplotlib内置的工具项

由源码可知,matplotlib.backend_tools.default_tools变量为字典类型,实例化了基于matplotlib.backend_tools.toolbase类定义的内置工具项。

源码

default_tools = {'home': toolhome, 'back': toolback, 'forward': toolforward,
     'zoom': toolzoom, 'pan': toolpan,
     'subplots': 'toolconfiguresubplots',
     'save': 'toolsavefigure',
     'grid': toolgrid,
     'grid_minor': toolminorgrid,
     'fullscreen': toolfullscreen,
     'quit': toolquit,
     'quit_all': toolquitall,
     'allnav': _toolenableallnavigation,
     'nav': _toolenablenavigation,
     'xscale': toolxscale,
     'yscale': toolyscale,
     'position': toolcursorposition,
     _views_positions: toolviewspositions,
     'cursor': 'toolsetcursor',
     'rubberband': 'toolrubberband',
     'help': 'toolhelp',
     'copy': 'toolcopytoclipboard',
     }

验证

import matplotlib.pyplot as plt
import matplotlib as mpl
from pprint import pprint

plt.rcparams['toolbar'] = 'toolmanager'
fig = plt.gcf()
pprint(mpl.backend_tools.default_tools)

输出

{‘allnav’: <class ‘matplotlib.backend_tools._toolenableallnavigation’>,
 ‘back’: <class ‘matplotlib.backend_tools.toolback’>,
 ‘copy’: ‘toolcopytoclipboard’,
 ‘cursor’: ‘toolsetcursor’,
 ‘forward’: <class ‘matplotlib.backend_tools.toolforward’>,
 ‘fullscreen’: <class ‘matplotlib.backend_tools.toolfullscreen’>,
 ‘grid’: <class ‘matplotlib.backend_tools.toolgrid’>,
 ‘grid_minor’: <class ‘matplotlib.backend_tools.toolminorgrid’>,
 ‘help’: ‘toolhelp’,
 ‘home’: <class ‘matplotlib.backend_tools.toolhome’>,
 ‘nav’: <class ‘matplotlib.backend_tools._toolenablenavigation’>,
 ‘pan’: <class ‘matplotlib.backend_tools.toolpan’>,
 ‘position’: <class ‘matplotlib.backend_tools.toolcursorposition’>,
 ‘quit’: <class ‘matplotlib.backend_tools.toolquit’>,
 ‘quit_all’: <class ‘matplotlib.backend_tools.toolquitall’>,
 ‘rubberband’: ‘toolrubberband’,
 ‘save’: ‘toolsavefigure’,
 ‘subplots’: ‘toolconfiguresubplots’,
 ‘viewpos’: <class ‘matplotlib.backend_tools.toolviewspositions’>,
 ‘xscale’: <class ‘matplotlib.backend_tools.toolxscale’>,
 ‘yscale’: <class ‘matplotlib.backend_tools.toolyscale’>,
 ‘zoom’: <class ‘matplotlib.backend_tools.toolzoom’>}

使用工具栏管理器管理内置工具项

由源码可知默认工具栏模式toolbar2模式没有提供添加、删除工具项的接口。因此,管理工具栏需要使用工具栏管理器模式toolmanager,与该模式相关的重要定义有:

  • matplotlib.backend_bases.toolcontainerbase(toolmanager)类:工具栏容器的基类,定义了工具栏编辑的方法。构造函数参数为toolmanager,表示工具栏容器容纳的工具栏。
  • matplotlib.backend_managers.toolmanager(figure=none)类:管理用户触发工具栏工具项按钮而产生的动作。matplotlib.backend_tools.toolbase类:所有工具栏工具项的基类,所有工具项均由matplotlib.backend_managers.toolmanager实例化。
  • matplotlib.backend_tools.default_tools变量:字典类型,实例化基于matplotlib.backend_tools.toolbase类定义的内置工具项。
  • matplotlib.backend_tools.default_toolbar_tools变量:嵌套列表,以类似格式[[分组1, [工具1, 工具2 ...]], [分组2, [...]]]定义工具栏布局。
  • matplotlib.backend_tools.add_tools_to_container函数:设置toolbarmanager模式默认工具栏。

使用系统函数实现添加工具项

根据源码可知,matplotlib.backend_tools.add_tools_to_container函数可以设置toolbarmanager模式默认工具栏。

案例

案例说明:为工具栏添加全屏切换工具项。

import matplotlib.pyplot as plt
import matplotlib as mpl

plt.rcparams['toolbar'] = 'toolmanager'
fig = plt.gcf()
# 通过mpl.backend_tools.add_tools_to_container函数添加工具项
mpl.backend_tools.add_tools_to_container(fig.canvas.manager.toolbar, tools=[['foo', [ 'fullscreen']]])
plt.show()

案例解析:add_tools_to_container函数有两个参数containertools,由源码可知container参数的值应为fig.canvas.manager.toolbartools参数按照[[分组1, [工具1, 工具2 ...]], [分组2, [...]]]格式取值。

使用工具栏管理器实现添加、删除内置工具项

根据源码可知:

添加内置工具项有两种方法

  • toolbar对象可以通过add_tool方法添加内置工具项,参数为nametoolname为工具项的名称,tool为添加的工具项对应的类或者字符串。
  • toolbar对象可以通过add_toolitem方法添加内置工具项,参数为namegrouppositionimage_filedescriptiontogglename为工具项的名称,group为工具项所在组,position为工具项在组中的位置,取值为列表索引,一般取-1即在所在组末尾追加,设置为0即在所在组的首位,image_file为工具项图像,值为字符串,description为工具项描述, toggle为是否为切换式工具项,布尔值。
  • 删除内置工具项有两种方法
  • toolbar对象可以通过remove_toolitem方法删除内置工具项,参数为name,即工具项的名称。
  • toolmanager对象可以通过remove_tool方法删除内置工具项,参数为name,即工具项的名称。

案例

案例说明:删除向前工具项,添加全屏切换工具项。

import matplotlib.pyplot as plt
import matplotlib as mpl

plt.rcparams['toolbar'] = 'toolmanager'
fig = plt.gcf()

fig.canvas.manager.toolmanager.remove_tool('forward')
fig.canvas.manager.toolbar.remove_toolitem('back')
fig.canvas.manager.toolbar.add_tool('quit', 'foo')
fig.canvas.manager.toolbar.add_toolitem('fullscreen', 'foo', -1,'fullscreen','fullscreen',false) 

plt.show()

总结

通过工具栏管理器添加、删除内置工具项的方法很多种,需要注意调用对象、方法、参数,阅读下面的matplotlib源码可能会有所启发。

相关源码

matplotlib.backends.backend_qt5模块

class figuremanagerqt(figuremanagerbase):
 self.toolbar = self._get_toolbar(self.canvas, self.window)

 if self.toolmanager:
  backend_tools.add_tools_to_manager(self.toolmanager)
  if self.toolbar:
   backend_tools.add_tools_to_container(self.toolbar)

 if self.toolbar:
  self.window.addtoolbar(self.toolbar)
  tbs_height = self.toolbar.sizehint().height()
 else:
  tbs_height = 0
 def _get_toolbar(self, canvas, parent):
  # must be inited after the window, drawingarea and figure
  # attrs are set
  if matplotlib.rcparams['toolbar'] == 'toolbar2':
   toolbar = navigationtoolbar2qt(canvas, parent, true)
  elif matplotlib.rcparams['toolbar'] == 'toolmanager':
   toolbar = toolbarqt(self.toolmanager, self.window)
  else:
   toolbar = none
  return toolbar
 class toolbarqt(toolcontainerbase, qtwidgets.qtoolbar):
 def __init__(self, toolmanager, parent):
  toolcontainerbase.__init__(self, toolmanager)
  qtwidgets.qtoolbar.__init__(self, parent)
  self.setallowedareas(
   qtcore.qt.toptoolbararea | qtcore.qt.bottomtoolbararea)
  message_label = qtwidgets.qlabel("")
  message_label.setalignment(
   qtcore.qt.alignright | qtcore.qt.alignvcenter)
  message_label.setsizepolicy(
   qtwidgets.qsizepolicy(qtwidgets.qsizepolicy.expanding,
         qtwidgets.qsizepolicy.ignored))
  self._message_action = self.addwidget(message_label)
  self._toolitems = {}
  self._groups = {}

 def add_toolitem(
   self, name, group, position, image_file, description, toggle):

  button = qtwidgets.qtoolbutton(self)
  if image_file:
   button.seticon(navigationtoolbar2qt._icon(self, image_file))
  button.settext(name)
  if description:
   button.settooltip(description)

  def handler():
   self.trigger_tool(name)
  if toggle:
   button.setcheckable(true)
   button.toggled.connect(handler)
  else:
   button.clicked.connect(handler)

  self._toolitems.setdefault(name, [])
  self._add_to_group(group, name, button, position)
  self._toolitems[name].append((button, handler))

 def _add_to_group(self, group, name, button, position):
  gr = self._groups.get(group, [])
  if not gr:
   sep = self.insertseparator(self._message_action)
   gr.append(sep)
  before = gr[position]
  widget = self.insertwidget(before, button)
  gr.insert(position, widget)
  self._groups[group] = gr

 def toggle_toolitem(self, name, toggled):
  if name not in self._toolitems:
   return
  for button, handler in self._toolitems[name]:
   button.toggled.disconnect(handler)
   button.setchecked(toggled)
   button.toggled.connect(handler)

 def remove_toolitem(self, name):
  for button, handler in self._toolitems[name]:
   button.setparent(none)
  del self._toolitems[name]

 def set_message(self, s):
  self.widgetforaction(self._message_action).settext(s

matplotlib.backend_tools模块

def add_tools_to_container(container, tools=default_toolbar_tools):
 """
 add multiple tools to the container.

 parameters
 ----------
 container : container
  `backend_bases.toolcontainerbase` object that will get the tools added.
 tools : list, optional
  list in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
  where the tools ``[tool1, tool2, ...]`` will display in group1.
  see `add_tool` for details.
 """

 for group, grouptools in tools:
  for position, tool in enumerate(grouptools):
   container.add_tool(tool, group, position)
def add_tools_to_manager(toolmanager, tools=default_tools):
 """
 add multiple tools to a `.toolmanager`.

 parameters
 ----------
 toolmanager : `.backend_managers.toolmanager`
  manager to which the tools are added.
 tools : {str: class_like}, optional
  the tools to add in a {name: tool} dict, see `add_tool` for more
  info.
 """

 for name, tool in tools.items():
  toolmanager.add_tool(name, tool)

到此这篇关于python matplotlib工具栏源码探析二之添加、删除内置工具项的案例的文章就介绍到这了,更多相关python matplotlib内置工具项内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!