【问题标题】:Add toolbar button icon matplotlib添加工具栏按钮图标 matplotlib
【发布时间】:2018-10-24 14:17:31
【问题描述】:

我想在 matplotlib 图形工具栏中的自定义按钮上添加一个图标。我怎样才能做到这一点?到目前为止,我有以下代码:

import matplotlib
matplotlib.rcParams["toolbar"] = "toolmanager"
import matplotlib.pyplot as plt
from matplotlib.backend_tools import ToolToggleBase

class NewTool(ToolToggleBase):
    ...[tool code]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1, 2, 3], label="legend")
ax.legend()
fig.canvas.manager.toolmanager.add_tool("newtool", NewTool)
fig.canvas.manager.toolbar.add_tool(toolmanager.get_tool("newtool"), "toolgroup")
fig.show()

目前,它唯一要做的就是添加一个新按钮(它可以做我想要的),但图标只是工具的名称,即:“newtool”。如何为 png 图像等自定义图标更改此设置?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    该工具可以有一个属性image,它表示一个png图像的路径。

    import matplotlib
    matplotlib.rcParams["toolbar"] = "toolmanager"
    import matplotlib.pyplot as plt
    from matplotlib.backend_tools import ToolBase
    
    class NewTool(ToolBase):
        image = r"C:\path\to\hiker.png"
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot([1, 2, 3], label="legend")
    ax.legend()
    tm = fig.canvas.manager.toolmanager
    tm.add_tool("newtool", NewTool)
    fig.canvas.manager.toolbar.add_tool(tm.get_tool("newtool"), "toolgroup")
    plt.show()
    

    【讨论】:

    • 我试过这个解决方案,matplotlib docs上也有类似的解决方案,但我无法重现它。我收到以下错误: tm.add_tool("newtool", NewTool) AttributeError: 'NoneType' object has no attribute 'add_tool' plt.figure() 不包含画布似乎很奇怪。有什么想法吗?
    • 我在 Jupyter 中得到了相同的 AttributeError 但它在标准 IDE 中运行良好(即使我在两者中使用相同的解释器)。看起来它与后端的选择有关。
    • 因为这是我在搜索中偶然发现的第一页,而且我还想了解 Jupyter 中的 Matplotlib,这里有一个 Gihub 问题进行讨论:Make the toolbar customizable · Issue #270 · matplotlib/ipympl · GitHub
    猜你喜欢
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多