python matplotlib工具欄源碼探析二之添加、刪除內(nèi)置工具項(xiàng)的案例
從matplotlib工具欄源碼探析一(禁用工具欄、默認(rèn)工具欄和工具欄管理器三種模式的差異)一文可知matplotlib
內(nèi)置實(shí)現(xiàn)了多個(gè)工具項(xiàng)的實(shí)現(xiàn),而默認(rèn)工具欄中的工具項(xiàng)只是其中的一部分,有沒(méi)有方法直接管理工具欄,添加、刪除內(nèi)置工具項(xiàng)?
matplotlib內(nèi)置的工具項(xiàng)
由源碼可知,matplotlib.backend_tools.default_tools
變量為字典類型,實(shí)例化了基于matplotlib.backend_tools.ToolBase
類定義的內(nèi)置工具項(xiàng)。
源碼
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', }
驗(yàn)證
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'>}
使用工具欄管理器管理內(nèi)置工具項(xiàng)
由源碼可知默認(rèn)工具欄模式toolbar2
模式?jīng)]有提供添加、刪除工具項(xiàng)的接口。因此,管理工具欄需要使用工具欄管理器模式toolmanager
,與該模式相關(guān)的重要定義有:
matplotlib.backend_bases.ToolContainerBase(toolmanager)
類:工具欄容器的基類,定義了工具欄編輯的方法。構(gòu)造函數(shù)參數(shù)為toolmanager
,表示工具欄容器容納的工具欄。matplotlib.backend_managers.ToolManager(figure=None)
類:管理用戶觸發(fā)工具欄工具項(xiàng)按鈕而產(chǎn)生的動(dòng)作。matplotlib.backend_tools.ToolBase
類:所有工具欄工具項(xiàng)的基類,所有工具項(xiàng)均由matplotlib.backend_managers.ToolManager
實(shí)例化。matplotlib.backend_tools.default_tools
變量:字典類型,實(shí)例化基于matplotlib.backend_tools.ToolBase
類定義的內(nèi)置工具項(xiàng)。matplotlib.backend_tools.default_toolbar_tools
變量:嵌套列表,以類似格式[[分組1, [工具1, 工具2 ...]], [分組2, [...]]]
定義工具欄布局。matplotlib.backend_tools.add_tools_to_container
函數(shù):設(shè)置toolbarmanager
模式默認(rèn)工具欄。
使用系統(tǒng)函數(shù)實(shí)現(xiàn)添加工具項(xiàng)
根據(jù)源碼可知,matplotlib.backend_tools.add_tools_to_container
函數(shù)可以設(shè)置toolbarmanager
模式默認(rèn)工具欄。
案例
案例說(shuō)明:為工具欄添加全屏切換
工具項(xiàng)。
import matplotlib.pyplot as plt import matplotlib as mpl plt.rcParams['toolbar'] = 'toolmanager' fig = plt.gcf() # 通過(guò)mpl.backend_tools.add_tools_to_container函數(shù)添加工具項(xiàng) mpl.backend_tools.add_tools_to_container(fig.canvas.manager.toolbar, tools=[['foo', [ 'fullscreen']]]) plt.show()
案例解析:add_tools_to_container
函數(shù)有兩個(gè)參數(shù)container
和tools
,由源碼可知container
參數(shù)的值應(yīng)為fig.canvas.manager.toolbar
,tools
參數(shù)按照[[分組1, [工具1, 工具2 ...]], [分組2, [...]]]
格式取值。
使用工具欄管理器實(shí)現(xiàn)添加、刪除內(nèi)置工具項(xiàng)
根據(jù)源碼可知:
添加內(nèi)置工具項(xiàng)有兩種方法
toolbar
對(duì)象可以通過(guò)add_tool
方法添加內(nèi)置工具項(xiàng),參數(shù)為name
和tool
,name
為工具項(xiàng)的名稱,tool
為添加的工具項(xiàng)對(duì)應(yīng)的類或者字符串。toolbar
對(duì)象可以通過(guò)add_toolitem
方法添加內(nèi)置工具項(xiàng),參數(shù)為name
、group
、position
、image_file
、description
和toggle
,name
為工具項(xiàng)的名稱,group
為工具項(xiàng)所在組,position
為工具項(xiàng)在組中的位置,取值為列表索引,一般取-1
即在所在組末尾追加,設(shè)置為0
即在所在組的首位,image_file
為工具項(xiàng)圖像,值為字符串,description
為工具項(xiàng)描述,toggle
為是否為切換式工具項(xiàng),布爾值。- 刪除內(nèi)置工具項(xiàng)有兩種方法
toolbar
對(duì)象可以通過(guò)remove_toolitem
方法刪除內(nèi)置工具項(xiàng),參數(shù)為name
,即工具項(xiàng)的名稱。toolmanager
對(duì)象可以通過(guò)remove_tool
方法刪除內(nèi)置工具項(xiàng),參數(shù)為name
,即工具項(xiàng)的名稱。
案例
案例說(shuō)明:刪除向前
工具項(xiàng),添加全屏切換
工具項(xiàng)。
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()
總結(jié)
通過(guò)工具欄管理器添加、刪除內(nèi)置工具項(xiàng)的方法很多種,需要注意調(diào)用對(duì)象、方法、參數(shù),閱讀下面的matplotlib
源碼可能會(huì)有所啟發(fā)。
相關(guān)源碼
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)
到此這篇關(guān)于python matplotlib工具欄源碼探析二之添加、刪除內(nèi)置工具項(xiàng)的案例的文章就介紹到這了,更多相關(guān)python matplotlib內(nèi)置工具項(xiàng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python matplotlib實(shí)用繪圖技巧匯總
- python使用matplotlib顯示圖像失真的解決方案
- 基于python的matplotlib制作雙Y軸圖
- 用Python的繪圖庫(kù)(matplotlib)繪制小波能量譜
- python matplotlib繪圖實(shí)現(xiàn)刪除重復(fù)冗余圖例的操作
- Python基礎(chǔ)之畫(huà)圖神器matplotlib
- python讀取并顯示圖片的三種方法(opencv、matplotlib、PIL庫(kù))
- python 如何在 Matplotlib 中繪制垂直線
- 利用Python matplotlib繪制風(fēng)能玫瑰圖
- python 繪圖模塊matplotlib的使用簡(jiǎn)介
- python之 matplotlib和pandas繪圖教程
- Python繪圖庫(kù)Matplotlib的基本用法
相關(guān)文章
Python 實(shí)現(xiàn)文件的全備份和差異備份詳解
這篇文章主要介紹了Python 實(shí)現(xiàn)文件的全備份和差異備份詳解的相關(guān)資料,需要的朋友可以參考下2016-12-12Python連接SQL Server數(shù)據(jù)庫(kù)并實(shí)時(shí)讀取數(shù)據(jù)
在Python中,可以使用pyodbc庫(kù)來(lái)連接SQL Server數(shù)據(jù)庫(kù),并使用pandas庫(kù)來(lái)進(jìn)行數(shù)據(jù)處理,下面我們就來(lái)講講如何實(shí)時(shí)讀取SQL Server數(shù)據(jù)庫(kù)表,并將數(shù)據(jù)寫(xiě)入Excel文件,需要的可以參考下2023-12-12使用numpy轉(zhuǎn)換成cupy利用GPU執(zhí)行錯(cuò)誤
在使用PyInstaller打包Python程序時(shí),可能會(huì)遇到缺少模塊的錯(cuò)誤,尤其是在將Numpy轉(zhuǎn)換為CuPy以利用GPU加速時(shí),如果遇到ModuleNotFoundError,表明PyInstaller沒(méi)有包含一些隱式導(dǎo)入的包,解決方法是手動(dòng)將缺失的包添加到打包目錄中2024-09-09django使用django-apscheduler 實(shí)現(xiàn)定時(shí)任務(wù)的例子
今天小編就為大家分享一篇django使用django-apscheduler 實(shí)現(xiàn)定時(shí)任務(wù)的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07python根據(jù)json數(shù)據(jù)畫(huà)疫情分布地圖的詳細(xì)代碼
這篇文章主要介紹了python根據(jù)json數(shù)據(jù)畫(huà)疫情分布地圖的詳細(xì)代碼,掌握使用pyecharts構(gòu)建基礎(chǔ)的全國(guó)地圖可視化圖表,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12python3使用flask編寫(xiě)注冊(cè)post接口的方法
今天小編就為大家分享一篇python3使用flask編寫(xiě)注冊(cè)post接口的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12