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', 'Keyma<a>本文来源gao($daima.com搞@代@#码(网</a>p')) 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()