如何从matplotlib中删除工具栏按钮

问题描述 投票:0回答:1

我想从绘图工具栏(matplotlib)中删除一些按钮。

我看到有一些旧的解决方案:

How to modify the navigation toolbar easily in a matplotlib figure window?

但所有答案都使用GUI框架(QT,TKinter)。

有没有使用GUI框架的新解决方案?

enter image description here

python matplotlib
1个回答
3
投票

您可以在创建绘图对象之前添加以下代码行来执行此操作:

import matplotlib as mpl
mpl.rcParams['toolbar'] = 'None' 

如果要有选择地删除某些按钮,则需要重新定义toolitems变量:

from matplotlib import backend_bases
# mpl.rcParams['toolbar'] = 'None'
backend_bases.NavigationToolbar2.toolitems = (
        ('Home', 'Reset original view', 'home', 'home'),
        ('Back', 'Back to  previous view', 'back', 'back'),
        ('Forward', 'Forward to next view', 'forward', 'forward'),
        (None, None, None, None),
        ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
        (None, None, None, None),
        ('Save', 'Save the figure', 'filesave', 'save_figure'),
      )

我从原始变量mpl.backend_bases.NavigationToolbar2.toolitems中删除了两行,通常读取:

toolitems = (
    ('Home', 'Reset original view', 'home', 'home'),
    ('Back', 'Back to  previous view', 'back', 'back'),
    ('Forward', 'Forward to next view', 'forward', 'forward'),
    (None, None, None, None),
    ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'),
    ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'),
    ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'),
    (None, None, None, None),
    ('Save', 'Save the figure', 'filesave', 'save_figure'),
  )

编辑

我意识到它适用于后端'TkAgg'。对于后端'Qt5Agg',我们需要在修改toolitems之后再做一些猴子补丁。即:

if matplotlib.get_backend() == 'Qt5Agg':
    from matplotlib.backends.backend_qt5 import NavigationToolbar2QT
    def _update_buttons_checked(self):
        # sync button checkstates to match active mode (patched)
        if 'pan' in self._actions:
            self._actions['pan'].setChecked(self._active == 'PAN')
        if 'zoom' in self._actions:
            self._actions['zoom'].setChecked(self._active == 'ZOOM')
    NavigationToolbar2QT._update_buttons_checked = _update_buttons_checked
© www.soinside.com 2019 - 2024. All rights reserved.