美文网首页
qt中插入matplotlib动画不显示

qt中插入matplotlib动画不显示

作者: _void_ | 来源:发表于2018-10-25 14:58 被阅读0次

    有一次在Qt5中需要插入matplotlib中的画图。此时需导入

    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    

    FigureCanvas可作为QT控件加入UI中。这里我需要使用动画,就在FigureCanvas中的figure对象加入matplotlib.animation。但在调用按钮事件时,发现运行run时动画不加载,但是在调用画图事件里加断点debug却没问题。于是疯狂google,终于发现由于调用的动画函数animation.FuncAnimation(self.fig, self._animate, interval=self.interval_msec, blit=True)时,如果跳出按钮事件函数,该animation.FuncAnimation对象会被垃圾回收,所以显示不了。至于为什么debug可以,我猜是因为debug的垃圾回收机制不同吧。所以不能让animation.FuncAnimation对象被回收。解决办法也很简单。

        def start(self):
            if RealtimePlotter.ani is None:
                RealtimePlotter.ani = animation.FuncAnimation(self.fig, self._animate, interval=self.interval_msec, blit=True)
    

    类变量和静态变量不会在函数结束释放animation.FuncAnimation对象,应次先将类变量ani赋值为None,调用时进行赋值。

    相关文章

      网友评论

          本文标题:qt中插入matplotlib动画不显示

          本文链接:https://www.haomeiwen.com/subject/prtctqtx.html