如何在执行后自动关闭python动画

时间:2018-06-01 17:06:14

标签: python animation matplotlib

如何在自动执行后关闭python动画,以便可以执行其余的程序?例如,我有以下代码显示第一个动画,但我必须在代码进入第二个动画之前手动关闭它。

更新

import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
from matplotlib.animation import FuncAnimation

plt.style.use('classic')


def update(step,arr,axis,max_step):

    print(step,max_step)

    for i in range(5):
        for j in range(5):
            axis[i, j].xaxis.set_major_locator(plt.NullLocator())
            axis[i, j].yaxis.set_major_locator(plt.NullLocator())
            if arr[step][i, j] == 10:
                axis[i, j].imshow(Image.open('A.jpg'), cmap="bone")
            else:
                axis[i, j].imshow(Image.open('B.jpg'), cmap="bone")

    if step>=max_step:
        plt.close()
    return axis

if __name__ == '__main__':

    a = []
    for i in xrange(5):
        temp = np.zeros((5, 5))
        temp[i, i] = 10
        a.append(temp)

    fig, ax = plt.subplots(5, 5, figsize=(5, 5))
    fig.subplots_adjust(hspace=0, wspace=0)

    # FuncAnimation will call the 'update' function for each frame; here
    # animating over 10 frames, with an interval of 200ms between frames.
    anim = FuncAnimation(fig, update, frames=5, fargs=(a, ax,4), interval=200, repeat=False)

    plt.show()

    # repeat the above procedure
    a = []
    for i in xrange(5):
        temp = np.zeros((5, 5))
        temp[i, i] = 10
        a.append(temp)

    fig, ax = plt.subplots(5, 5, figsize=(5, 5))
    fig.subplots_adjust(hspace=0, wspace=0)

    # FuncAnimation will call the 'update' function for each frame; here
    # animating over 10 frames, with an interval of 200ms between frames.
    anim = FuncAnimation(fig, update, frames=5, fargs=(a, ax,4), interval=200, repeat=False)

    plt.show()

使用评论中的建议,上面的代码实际上有效,但我也收到了这个错误:

(0, 4)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)
Exception in Tkinter callback
Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1536, in __call__
    return self.func(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 587, in callit
    func(*args)
  File "/Users/asgharis/PycharmProjects/Q_Network/venv/lib/python2.7/site-packages/matplotlib/backends/_backend_tk.py", line 310, in idle_draw
    self.draw()
  File "/Users/asgharis/PycharmProjects/Q_Network/venv/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 13, in draw
    tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2)
  File "/Users/asgharis/PycharmProjects/Q_Network/venv/lib/python2.7/site-packages/matplotlib/backends/tkagg.py", line 34, in blit
    dataptr, colormode, bboxptr)
TclError: this isn't a Tk application
(0, 4)
(0, 4)
(1, 4)
(2, 4)
(3, 4)
(4, 4)

是否有解决此错误的想法?

0 个答案:

没有答案