如何在我的wxpython绘图画布中添加matplotlib.widget.Button?

时间:2018-03-15 08:23:56

标签: python matplotlib wxpython wxpython-phoenix matplotlib-widget

我一直在尝试将matplotlib.widget.Button添加到我的matplotlib绘图画布中,该画布已集成在wxPython中,但没有成功。

这是生成画布的代码:

    from matplotlib.figure import Figure
    from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
    import matplotlib.pyplot as plt

    import matplotlib
    matplotlib.use('WXAgg')

    from matplotlib.widgets import Button

    import wx


    self.figure = Figure()
    self.axes = self.figure.add_subplot(111)
    self.canvas = FigureCanvas(self, -1, self.figure)
    self.sizer = wx.BoxSizer(wx.VERTICAL)
    self.sizer.Add(self.canvas, proportion=1, flag=wx.ALL | wx.GROW)
    self.SetSizer(self.sizer)
    self.Fit()
    self.canvas.draw()


    plot_object = self.axes.pcolormesh(combo_value.T, cmap='rainbow', 
                                           norm=colors.LogNorm(vmin=vmin_value, vmax=vmax_value))

    self.canvas.draw()

如何在wxPython中为此matplotlib图的轴添加按钮?我试图遵循这个例子:https://matplotlib.org/examples/widgets/buttons.html,但没有成功,因为你在wxPython的matplotlib中没有使用plt.axes

我尝试过以下操作,实际上确实在画布上添加了一个按钮,但它不是交互式的。

    axprev = self.figure.add_axes([0.7, 0.01, 0.1, 0.075])
    bprev = Button(axprev, 'Previous')
    bprev.on_clicked(self.test())

def test(self):
    print('Called')

这就是GUI画布现在的样子: Button that's not interactive

1 个答案:

答案 0 :(得分:0)

这似乎是理解使用matplotlib的面向对象方式的问题。大多数pyplot命令直接具有OO等效值作为所使用的相应图形或轴的方法。

以下是将示例转换为面向对象的样式。 (pyplpot仅用于创建图形并显示窗口,您知道如何在wx中执行此操作。)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

freqs = np.arange(2, 20, 3)

fig = plt.figure()   # use matplotlib.figure.Figure() for embedding
ax = fig.add_subplot(111)
fig.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = ax.plot(t, s, lw=2)


class Index(object):
    ind = 0

    def next(self, event):
        self.ind += 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        fig.canvas.draw_idle()

    def prev(self, event):
        self.ind -= 1
        i = self.ind % len(freqs)
        ydata = np.sin(2*np.pi*freqs[i]*t)
        l.set_ydata(ydata)
        fig.canvas.draw_idle()

callback = Index()
axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])
axnext = fig.add_axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)

plt.show()  # replace with your GUIs start of the mainloop

在函数或方法中使用它时,不要忘记创建Buttons类变量,

    self.bnext = Button(axnext, 'Next')
    self.bnext.on_clicked(callback.next)
    self.bprev = Button(axprev, 'Previous')
    self.bprev.on_clicked(callback.prev)