我试图弄清楚如何在PyQT GUI中嵌入Matplotlib动画(使用funcAnimation)。令人惊讶的是,我无法在网上找到......这个链接基本上就是它,而且很难遵循:
Can I use Animation with Matplotlib widget for pyqt4?
以下代码是使用Matplotlib的非常简单的动画。它只是一个在屏幕上移动的圆圈,它工作正常:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation
fig,ax = plt.subplots()
ax.set_aspect('equal','box')
circle = Circle((0,0), 1.0)
ax.add_artist(circle)
ax.set_xlim([0,10])
ax.set_ylim([-2,2])
def animate(i):
circle.center=(i,0)
return circle,
anim = animation.FuncAnimation(fig,animate,frames=10,interval=100,repeat=False,blit=True)
plt.show()
以下是我在PyQT GUI中嵌入此动画的尝试。 (我相信我有prevented the reference to the animation object from being garbage collected来称呼self.anim
):
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation
class Window(QtGui.QDialog): #or QtGui.QWidget ???
def __init__(self):
super(Window, self).__init__()
self.fig = plt.figure()
self.canvas = FigureCanvas(self.fig)
self.button = QtGui.QPushButton('Animate')
self.button.clicked.connect(self.animate)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def animate(self):
self.ax = self.fig.add_subplot(111) # create an axis
self.ax.hold(False) # discards the old graph
self.circle = Circle((0,0), 1.0)
self.ax.add_artist(self.circle)
self.ax.set_xlim([0,10])
self.ax.set_ylim([-2,2])
self.anim = animation.FuncAnimation(self.fig,self.animate_loop,frames=10,interval=100,repeat=False,blit=False)
plt.show()
def animate_loop(self,i):
self.circle.center=(i,0)
return self.circle,
w = Window()
w.show()
运行此代码会显示GUI,但是当我点击" Animate"按钮,什么都没发生。控制台中甚至没有给出错误消息。任何见解都会非常感激!