Reputation: 115
I uses the animation.FuncAnimation from matplotlib to view camera pictures. I use python 3.6. Is there a possibility to attach a function to the close event?
My goal is: If I close the window, I would also like to close the camera. I just want to close the window of the animation not the whole python application. What is the best way to do this?
from Class.LiveView import LiveView
from Class.PixelFormat import PixelFormat
import matplotlib.pyplot as plt
import matplotlib.animation as animation
class Viewer(object):
"""show picture"""
def __init__ (self):
self.cap = LiveView()
self.cap.startcam()
self.cap.autoExposureTime()
def plotPicLive(self):
self.cap.startGetPic(PixelFormat.Mono8)
fig = plt.figure()
frame = self.cap.getPic()
fig.add_subplot(1,1,1)
im = plt.imshow(frame, animated=True)
def updatefig(*args):
frame = self.cap.getPic()
im.set_array(frame)
return im
ani = animation.FuncAnimation(fig,updatefig, interval=1)
plt.show()
def close(self):
self.cap.stopPic()
self.cap.close()
self.cap.cleanCam()
This is only a example class.
thank you in advance.
Upvotes: 1
Views: 4468
Reputation: 339580
Matplotlib has a close_event
. This is unfortunately not well documented in the event handling guide but there is an example on how to use it. To cite the example:
from __future__ import print_function
import matplotlib.pyplot as plt
def handle_close(evt):
print('Closed Figure!')
fig = plt.figure()
fig.canvas.mpl_connect('close_event', handle_close)
plt.text(0.35, 0.5, 'Close Me!', dict(size=30))
plt.show()
In your case, (under the assumption that the rest of the code works fine) this could be directly used as
# .....
ani = animation.FuncAnimation(fig,updatefig, interval=1)
fig.canvas.mpl_connect('close_event', self.close)
plt.show()
def close(self):
self.cap.stopPic()
self.cap.close()
self.cap.cleanCam()
Upvotes: 4