Matplotlib 使用PyQt4使用按钮更新主窗口上的图形

Matplotlib 使用PyQt4使用按钮更新主窗口上的图形,matplotlib,widget,pyqt4,embed,Matplotlib,Widget,Pyqt4,Embed,我在模仿。我成功地在我的GUI中嵌入了一个图形,当我按下按钮时,它可以完美地工作。但问题是,当我第二次或更多次单击按钮时,它不会更新。它抛出以下错误 QLayout: Attempting to add QLayout "" to QWidget "centralwidget", which already has a layout 以下是我目前的代码: class MyMplCanvas(FigureCanvas): """Ultimately, this is a QWidget

我在模仿。我成功地在我的GUI中嵌入了一个图形,当我按下按钮时,它可以完美地工作。但问题是,当我第二次或更多次单击按钮时,它不会更新。它抛出以下错误

QLayout: Attempting to add QLayout "" to QWidget "centralwidget", which already has a layout
以下是我目前的代码:

class MyMplCanvas(FigureCanvas):
    """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.)."""

    def __init__(self, parent=None, width=5, height=4, dpi=100, stores = [], prices = []):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        self.prices = prices
        self.stores = stores
        self.compute_initial_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.setMinimumSize(400, 400)
        self.setMaximumSize(800, 300)

    def compute_initial_figure(self):
        pass


class MyStaticMplCanvas(MyMplCanvas):
    """Simple canvas with a sine plot."""

    def compute_initial_figure(self):
        self.axes.clear() # To clear the axis every time and make new plot 
        y_pos = np.arange(4)
        self.axes.bar(y_pos, self.prices)
        self.axes.set_xticks(y_pos, minor=False)
        self.axes.set_xticklabels(self.stores, fontdict=None, minor=False)
对于按钮,我有以下方法

def button_click(self):
.......
     # Here is some logic that return prices and stores list which is used in self.sc
     self.l = QtGui.QVBoxLayout(self.centralwidget)
     self.sc = MyStaticMplCanvas(self.centralwidget, width=5, height=4, dpi=100, stores=stores, prices= prices)
     self.l.addWidget(self.sc)
if (self.l.count() > 0): self.sc.deleteLater() # Added in new Edit but it also does not work
我尝试了很多选择:

1. self.sc.deleteLater() # It just removes the graph from GUI
2. self.sc.axes.clear() and self.sc.axes.cla() # Does nothing but returns above mentioned error
3. I deleted the layout from central widget and set it again but still nothing happened.
4. I tried this too --> `if (self.l.count() > 0): self.sc.deleteLater()` but it just delete the whole graph

我哪里做错了?请导游。谢谢

不清楚为什么要将FigureCanvas第二次添加到GUI中。但是,由于我们对这个问题没有明确的认识,所以无法提供帮助。我可能是以一种幼稚或错误的方式这样做的。但目标是用新数据更新图表,每当我点击按钮时,我都会得到
商店
价格
的列表。有更好的办法吗?我刚发现你是对的。我把FigureCanvas放回了_uinit__;()中,它按照我想要的方式工作。谢谢你指出这一点