我正试着在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
个类应该做什么.