2017-09-06 155 views
0

我使用matplotlib中的animation.FuncAnimation来查看相机图片。我使用python 3.6。是否有可能将函数附加到关闭事件?我的目标是: 如果我关上窗户,我还想关闭相机。我只想关闭动画的窗口,而不是整个python应用程序。做这个的最好方式是什么?matplotlib动画关闭事件

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() 

这只是一个示例类。

谢谢你提前。

回答

0

Matplotlib有一个close_event。不幸的是,在event handling guide中没有很好的记录,但是有关于如何使用它的an 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() 

在你的情况,这可以直接用作

 # ..... 

     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() 
(即代码的其他工作正常的假设下)