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

2024-05-23 17:15:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从打印工具栏(matplotlib)中删除一些按钮。在

我发现有一些老办法:

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

但是所有的答案都使用GUI框架(QT、TKinter)。在

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

enter image description here


Tags: thetoin框架matplotlibgui按钮how
1条回答
网友
1楼 · 发布于 2024-05-23 17:15:52

可以通过在创建plot对象之前添加以下代码行来完成此操作:

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

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

^{pr2}$

我已经从原始变量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之后进行一些额外的monkey修补。即:

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

相关问题 更多 >