我正试着在toolbar的基础上加一个按钮.该按钮是继承ToolToggleBase的自定义类.在我的定制SelectButton类中,我想传递几个参数,但我收到了一个错误:

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


def simple_plot(mat):
    fig = plt.figure()
    ax = fig.add_subplot()
    ax.plot(np.reshape(mat, [-1, 1]))
    ax.grid(True)
    ax.legend()
    tm = fig.canvas.manager.toolmanager
    tm.add_tool("CustomButton", SelectButton(fig, ax))
    fig.canvas.manager.toolbar.add_tool(tm.get_tool("CustomButton"), "toolgroup")
    return fig, ax


class SelectButton(ToolToggleBase):
    default_toggled = False

    def __init__(self, fig1, ax1, *args, **kwarg):
        super().__init__(*args, **kwarg)
        print("fig: ", fig1)
        print("ax: ", ax1)


x = [1, 2, 3]
fig, ax = simple_plot(x)
plt.show()

结果是:

Super().init(*args,**kwargs) TypeError:init()缺少两个必需的位置参数:""Tool Manager""和""Name""

但是,如果我不传递任何参数,而只传递类名,则一切都会按预期进行:

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


def simple_plot(mat):
    fig = plt.figure()
    ax = fig.add_subplot()
    ax.plot(np.reshape(mat, [-1, 1]))
    ax.grid(True)
    ax.legend()
    tm = fig.canvas.manager.toolmanager
    tm.add_tool("CustomButton", SelectButton)
    fig.canvas.manager.toolbar.add_tool(tm.get_tool("CustomButton"), "toolgroup")
    return fig, ax


class SelectButton(ToolToggleBase):
    default_toggled = False

    def __init__(self, *args, **kwarg):
        super().__init__(*args, **kwarg)

x = [1, 2, 3]
fig, ax = simple_plot(x)
plt.show()

我知道当使用类的实例而不是类名时,我必须错误地调用add_tool,但我不能理解如果我想要将参数传递给SelectButton个类应该做什么.

推荐答案

您需要将类SelectButton本身传递给add_tool,而不是将其实例SelectButton()传递给add_tool.您应该将附加参数作为kwargs进行传递:

def simple_plot(mat):
    fig = plt.figure()
    ax = fig.add_subplot()
    # ...
    tm = fig.canvas.manager.toolmanager
    tm.add_tool("CustomButton", SelectButton, fig=fig, ax=ax)
    fig.canvas.manager.toolbar.add_tool(tm.get_tool("CustomButton"), "toolgroup")
    return fig, ax


class SelectButton(ToolToggleBase):
    default_toggled = False

    def __init__(self, *args, fig, ax, **kwarg):
        super().__init__(*args, **kwarg)
        print("fig: ", fig)
        print("ax: ", ax) 

这将打印以下内容:

fig:  Figure(640x480)
ax:  Axes(0.125,0.11;0.775x0.77)

如果出于某种原因,您确实想使用args而不是kwargs,那么您应该使用other answer中所示的部分.只将前两个参数传递给Superper,然后自己使用其余的参数,这与其说是一种解决方案,不如说是一种技巧,因为这取决于matplotlib的实现细节:

tm.add_tool("CustomButton", SelectButton, fig, ax)

def __init__(self, *args, **kwarg):
    super().__init__(*args[:2], **kwarg)
    print("fig: ", args[2])
    print("ax: ", args[3])

Python相关问答推荐

将numpy矩阵映射到字符串矩阵

Odoo -无法比较使用@api.depends设置计算字段的日期

返回nxon矩阵的diag元素,而不使用for循环

Python中的嵌套Ruby哈希

用Python解密Java加密文件

计算组中唯一值的数量

如何获取numpy数组的特定索引值?

SQLAlchemy Like ALL ORM analog

为什么NumPy的向量化计算在将向量存储为类属性时较慢?'

给定高度约束的旋转角解析求解

合并帧,但不按合并键排序

在单次扫描中创建列表

Flask Jinja2如果语句总是计算为false&

Python Pandas—时间序列—时间戳缺失时间精确在00:00

剪切间隔以添加特定日期

导入错误:无法导入名称';操作';

如果包含特定值,则筛选Groupby

如何使用matplotlib查看并列直方图

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

Polars时间戳同步延迟计算