I am trying to figure out how to embed a Matplotlib animation (using funcAnimation) within a PyQT GUI. There is surprisingly little that I could find on the web...this link was basically it, and it was difficult to follow:
Can I use Animation with Matplotlib widget for pyqt4?
The following code is a very simple animation using Matplotlib. It is just a circle moving across the screen, and it works fine:
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()
The following is my attempt at embedding this animation within a PyQT GUI. (I believe I have prevented the reference to the animation object from being garbage collected by calling it 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()
Running this code brings up the GUI, but when I click the "Animate" button, nothing happens at all. There is not even an error message given in the console. Any insight would be much appreciated!