首页 > 编程技术 > python

python matplotlib工具栏源码探析三之添加、删除自定义工具项的案例详解

发布时间:2021-2-25 20:00

matplotlib工具栏源码探析二(添加、删除内置工具项)探讨了工具栏内置工具项的管理,除了内置工具项,很多场景中需要自定义工具项,官方给出了案例https://matplotlib.org/gallery/user_interfaces/toolmanager_sgskip.html,主要基于matplotlib.backend_managers.ToolManager类实现,即使用工具栏管理器模式。

官方案例解析

下面对官方案例关键点做注释说明。

import matplotlib.pyplot as plt
# 设置工具栏使用工具栏管理器模式
plt.rcParams['toolbar'] = 'toolmanager'
# 导入工具项的基类ToolBase和ToolToggleBase
from matplotlib.backend_tools import ToolBase, ToolToggleBase

# 因为工具项必须以类的形式添加,所以创建自定义基本工具项类,基类为ToolBase
class ListTools(ToolBase):
 # 该工具项的功能为列出工具栏管理器管理的所有工具项
 """List all the tools controlled by the `ToolManager`."""
 # 设置默认快捷键和工具项描述
 default_keymap = 'm'
 description = 'List Tools'
 
 # 定义工具项被触发时的动作
 def trigger(self, *args, **kwargs):
  print('_' * 80)
  print("{0:12} {1:45} {2}".format(
   'Name (id)', 'Tool description', 'Keymap'))
  print('-' * 80)
  # 获取工具栏管理器管理的所有工具项
  tools = self.toolmanager.tools
  # 输出各个工具项
  for name in sorted(tools):
   if not tools[name].description:
    continue
   keys = ', '.join(sorted(self.toolmanager.get_tool_keymap(name)))
   print("{0:12} {1:45} {2}".format(
    name, tools[name].description, keys))
  print('_' * 80)
  print("Active Toggle tools")
  print("{0:12} {1:45}".format("Group", "Active"))
  print('-' * 80)
  for group, active in self.toolmanager.active_toggle.items():
   print("{0:12} {1:45}".format(str(group), str(active)))

# 基于ToolToggleBase创建自定义切换式工具项,切换式工具项在触发时会在生效和失效两种状态之间切换
class GroupHideTool(ToolToggleBase):
 # 该工具项的功能为根据分组切换显示/隐藏数据元素
 """Show lines with a given gid."""
 # 设置默认快捷键和工具项描述
 default_keymap = 'G'
 description = 'Show by gid'
 default_toggled = True
 
 # 构造函数的参数gid为数据元素的分组
 def __init__(self, *args, gid, **kwargs):
  self.gid = gid
  super().__init__(*args, **kwargs)
 # 定义工具项生效时的方法
 def enable(self, *args):
  self.set_lines_visibility(True)
 # 定义工具项失效时的方法
 def disable(self, *args):
  self.set_lines_visibility(False)

 def set_lines_visibility(self, state):
  for ax in self.figure.get_axes():
   for line in ax.get_lines():
    if line.get_gid() == self.gid:
     line.set_visible(state)
  # 注意!在图像生成之后,修改图像中的元素必须重绘
  self.figure.canvas.draw()


fig = plt.figure()
# 注意通过gid属性可以为数据元素分组
plt.plot([1, 2, 3], gid='mygroup')
plt.plot([2, 3, 4], gid='unknown')
plt.plot([3, 2, 1], gid='mygroup')

# 将自定义的工具项添加添加到工具栏管理器,格式为 工具项名称 工具项类 其他参数
fig.canvas.manager.toolmanager.add_tool('List', ListTools)
fig.canvas.manager.toolmanager.add_tool('Show', GroupHideTool, gid='mygroup')

# 可以反复添加已存在的工具项
# Add an existing tool to new group `foo`.
# It can be added as many times as we want
fig.canvas.manager.toolbar.add_tool('zoom', 'foo')

# 删除工具项
# Remove the forward button
fig.canvas.manager.toolmanager.remove_tool('forward')

# 新添加到工具栏管理器的工具项还不能直接使用,需要通过toolbar对象添加到当前工具栏
# 如果不将自定义的工具项添加到工具栏管理器,直接使用toolbar对象添加则会报错
# 将自定义的工具项Show添加到内置的navigation组的特定位置(即组内第2个位置)
# To add a custom tool to the toolbar at specific location inside
# the navigation group
fig.canvas.manager.toolbar.add_tool('Show', 'navigation', 1)
#fig.canvas.manager.toolbar.add_tool('List', 'navigation', 2)
plt.show()

官方案例运行结果

运行后自定义的Show按钮处于生效状态,3条线全部显示。

在这里插入图片描述

点击Show按钮,使之处理失效状态,mygroup组的两条线不再显示。

在这里插入图片描述

由于案例中仅将List工具项添加到工具栏管理器,但是没有添加到工具栏中,因此List工具项未在工具栏中显示。但是List工具项的快捷键m是生效的,在界面上按快捷键m,控制台输出以下信息。

________________________________________________________________________________
Name (id) Tool description        Keymap
--------------------------------------------------------------------------------
List   List Tools         m
Show   Show by gid         G
allnav  Enable all axes toolmanager     a
back   Back to previous view       MouseButton.BACK, backspace, c, left
copy   Copy the canvas figure to clipboard   cmd+c, ctrl+c
fullscreen Toggle fullscreen mode      ctrl+f, f
grid   Toggle major grids       g
grid_minor Toggle major and minor grids
help   Print tool list, shortcuts and description f1
home   Reset original view       h, home, r
nav   Enable one axes toolmanager     1, 2, 3, 4, 5, 6, 7, 8, 9
pan   Pan axes with left mouse, zoom with right  p
quit   Quit the figure        cmd+w, ctrl+w, q
quit_all  Quit all figures
save   Save the figure        ctrl+s, s
subplots  Configure subplots
xscale  Toggle scale X axis       L, k
yscale  Toggle scale Y axis       l
zoom   Zoom to rectangle        o
________________________________________________________________________________
Active Toggle tools
Group  Active
--------------------------------------------------------------------------------
default  None
None   {'Show'}

总结

matplotlib支持两种工具项:基本工具项(基类ToolBase)和切换式工具项(基类ToolToggleBase)。
基本工具项需要注意定义trigger方法,即工具项被触发时的动作。
切换式工具项需要注意定义enabledisable方法,即生效和失效两种状态的动作,如方法定义中牵扯到修改图像,需要注意重绘图像。
注意添加自定义工具项的流程!先将自定义的工具项添加到工具栏管理器,然后再添加到当前工具栏!内置工具项之所以不用添加到工具栏管理器是因为它们本身就已经添加在工具栏管理器!

到此这篇关于matplotlib工具栏源码探析三之添加、删除自定义工具项的文章就介绍到这了,更多相关matplotlib工具栏内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: