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方法,即工具項被觸發時的動作,
切換式工具項需要注意定義enable和disable方法,即生效和失效兩種狀態的動作,如方法定義中牽扯到修改影像,需要注意重繪影像,
注意添加自定義工具項的流程!先將自定義的工具項添加到工具列管理器,然后再添加到當前工具列!內置工具項之所以不用添加到工具列管理器是因為它們本身就已經添加在工具列管理器!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/249899.html
標籤:python
上一篇:成員變數和區域變數
