You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt5嵌入matplotlib绘图点击按钮后画布无法刷新如何解决

问题原因

该问题为macOS环境下PyQt5 5.13版本与matplotlib 3.3.4版本组合的常见渲染同步问题:canvas.draw()完成matplotlib侧的图像渲染后,未主动触发Qt层的控件重绘,因此界面看不到更新效果。

修复方案

方案1:快速适配现有代码

仅需在update_plot方法的self.canvas.draw()后新增一行Qt控件重绘触发逻辑即可:

def update_plot(self):
    self.ydata = self.ydata[1:] + [random.randint(0, 10)]
    self.canvas.axes.cla()  
    self.canvas.axes.plot(self.xdata, self.ydata, 'r')
    self.canvas.draw()
    self.canvas.update() # 新增本行触发Qt控件重绘
    print("Plotted!")

方案2:更高性能的动态绘图实现

无需每次清空坐标轴重绘,通过缓存折线实例直接更新数据,既提升运行效率,也能规避版本兼容导致的刷新问题:

  1. 初始化时首次绘制并缓存折线对象
class Window(QWidget):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        vbox = QVBoxLayout()
        self.setLayout(vbox)

        self.canvas = MplCanvas(parent=None, width=5, height=4, dpi=100)
        self.btn = QPushButton("Plot")
        self.btn.clicked.connect(self.update_plot)

        vbox.addWidget(self.canvas)
        vbox.addWidget(self.btn)

        self.n_data = 50
        self.xdata = list(range(self.n_data))
        self.ydata = [random.randint(0, 10) for i in range(self.n_data)]

        # 新增:首次绘图并缓存折线实例
        self._line, = self.canvas.axes.plot(self.xdata, self.ydata, 'r')
        self.show()
  1. 修改update_plot方法直接更新数据
def update_plot(self):
    self.ydata = self.ydata[1:] + [random.randint(0, 10)]
    self._line.set_ydata(self.ydata)
    self.canvas.draw()
    self.canvas.flush_events()
    print("Plotted!")

内容的提问来源于stack exchange,提问作者Drachen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:06:02