【问题标题】:Remove toolbar buttons in matplotlib删除 matplotlib 中的工具栏按钮
【发布时间】:2019-08-27 15:56:39
【问题描述】:

我正在尝试删除除“保存”按钮之外的所有工具栏按钮。 我设法删除了按钮,但找不到删除“配置子图”按钮的方法。

这是一个简单的代码,只是为了说明我如何尝试删除按钮:

import matplotlib.pyplot as plt
plt.rcParams['toolbar'] = 'toolmanager'

# I managed to find the buttons' names while reading the backend_bases.py
# I didn't find the subplot configuration button name so i didn't include it here
buttons_names = ['forward', 'back', 'pan', 'zoom', 'home', 'help']

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2], [1, 2])

# removing buttons using
for button in buttons_names:
    fig.canvas.manager.toolmanager.remove_tool(button)

plt.show()

我查看了 backend_bases.py 并评论了 subplots 元组,现在看起来像这样:(我不知道是否在其他地方引用了“subplots configuration”按钮以删除该按钮)

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'),
      )

当我运行上面的代码时,它也会显示一个警告: UserWarning: Treat the new Tool classes introduced in v1.5 as experimental for now, the API will likely change in version 2.1, and some tools might change name 'experimental for now, the API will likely change in ' +

我查看了其他解决方案,但没有一个对我有用,其中一些使用 gui 框架,这不是我想要的。

是否有任何其他方法可以删除该按钮,或者是否有子图配置按钮的名称可以包含在上述代码的buttons_names 列表中?

更新:好的,看来问题与python版本有关。我使用的是 python 3.7.0。我更新到 3.7.4,将 'subplots' 添加到 buttons_names 列表中,它起作用了。但是有两个问题:

  1. 显示图表时,会显示警告:
Treat the new Tool classes introduced in v1.5 as experimental for now, the API will likely change in version 2.1 and perhaps the rcParam as well
C:/Users/usr/Documents/MyPrograms/Python/Daily Expense/Chart.py:36: UserWarning: The new Tool classes introduced in v1.5 are experimental; their API (including names) will likely change in future versions.
fig = plt.figure()
  1. 工具栏现在显示在顶部,它曾经位于图表下方,我想让它像以前一样显示在图表下方。

目前我正在使用 Python 3.7.4,matplotlib 版本 3.1.1,Windows 10

我该如何解决这两件事?

【问题讨论】:

  • 你使用什么系统,什么版本的 Python 和 Matplotlib? subplots" 在 Linux Mint 19.2、Python 3.7.4、matplotlib 3.1.1 上删除了这个按钮。似乎它也删除了其他用户的按钮。所以也许这取决于版本或系统。
  • 我已经更新了问题并提供了有关我正在使用的版本的信息

标签: python python-3.x matplotlib


【解决方案1】:

显然名字是"subplots"

fig.canvas.manager.toolmanager.remove_tool("subplots")

【讨论】:

  • 这正是我首先提出这个问题的原因,我尝试了“subplots”这个名称,但程序捕获了一个异常:AttributeError: 'NoneType' object has no attribute 'destroy'。正如我在问题中所说,我在toolitems 中评论了“子图”元组,我取消了该元组的注释并重新运行了脚本,但仍然捕获了AttributeError 异常。