我正在尝试用tkinter创建一个GUI,它向我展示我捕获的事件的动画,当我点击一个按钮时,应该显示下一个事件 . 到目前为止,我的代码正是如此,但我遇到的问题是,当我点击按钮显示下一个事件时,旧事件不会从画布中清除,因此两者重叠,或者当我点击更多时显示动画 .

我的代码看起来像这样:

import matplotlib.pyplot as plt
from matplotlib import animation
import Tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Framenumber of Images that shall be animated
# shape(Frames) = (number_of_events, frames_per_event)
Frames = get_Frames(tdms_file)

# event that shall be analysed
k = 0

fig = plt.figure()
ax = fig.add_subplot(111)

root = tk.Tk()
root.title("My Animation GUI")

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.show()
canvas.get_tk_widget().grid(row=0,column=1)

def event_animation(Frames, ax, k, canvas):

    ims = []

    for i in range(len(Frames[k])):

        Image = get_image(Frames[k], i)     # function that grabs the images from a different file 
        im =  ax.imshow(Image, cmap='gray', animated=True)
        ims.append([im])

    ani = animation.ArtistAnimation(fig, ims, interval=25, blit=True, repeat_delay=1000)
    canvas.show()

# show next event
def next_event():
    global k
    k += 1
    ani_show = event_animation(Frames, ax, k, canvas)

# show previous event
def prev_event():
    global k
    k -= 1
    ani_show = event_animation(Frames, ax, k, canvas)

prev_cell_button = tk.Button(root, text='<--', width=10, command = prev_cell)
prev_cell_button.grid(row=0, column=0)
next_cell_button = tk.Button(root, text='-->', width=10, command = next_cell)
next_cell_button.grid(row=0, column=2)

tk.mainloop()

我已经尝试在创建新动画之前用 ax.cla() 清除轴并编辑我的动画功能,如下例所示:stop / start / pause in python matplotlib animation

创建动画的功能如下所示:

def event_Funcanimation(Frames, ax, k, canvas):

    Image = get_image(Frames[k], 0)
    im = ax.imshow(Image, cmap='gray', animated=True)

    def ani_iterator():
        i = 0
        while i < len(Frames[k]):
            if not stop:

                Image = get_image(Frames[k], i)
                i += 1
                yield Image


    def show_image(ani_iterator):
        Image = ani_iterator
        im.set_array(Image)
        return im,

    ani = animation.FuncAnimation(fig, show_image, ani_iterator, 
                                  blit=True, interval=25, repeat = True)
    canvas.draw()
    return ani

当我点击其中一个按钮时,while循环中的 stop 变量将被更改 . 我知道这对我的代码无论如何都有用 .

现在的问题是,动画在画布中保持循环,当新动画启动时,它们会重叠 . 如果在开始新动画之前有可能从画布中清除动画,我认为这个问题可以很容易地解决 . 但我找不到任何可以解决我的问题的解决方案 . 我想要动画循环,所以设置 repeat = False 不是一个选项 . 这也没有解决问题,因为动画仍然会重叠,除非它们已经完成 .

在此先感谢您的帮助 .