tkinter 中的 Matplotlib 动画不会停止循环

Sim*_*get 1 python matplotlib

我在 tkinter 中运行了这个 matplotlib 动画,它工作正常,但它永远不会停止循环,当我按“X”时,窗口关闭,但我必须使用任务管理器强制关闭它。

这是我尝试设置它的示例代码:

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

import tkinter as tk
from tkinter import *

class Grapher(tk.Tk): # inherit Tk()
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)   
        tk.Tk.wm_title(self, "Quarantined-Grapher")

        self.fig = plt.figure()
        ax = plt.axes(xlim=(0,2), ylim=(0, 100))

        N = 4 # amount of lines
        self.lines = [plt.plot([], [])[0] for _ in range(N)]

        # give the figure and the root(which is self) to the "canvas"
        self.canvas = FigureCanvasTkAgg(self.fig, self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack()

        anim = animation.FuncAnimation(self.fig, self.animate, init_func=self.init,
                                        frames=100, interval=1000, blit=True)
    def init(self):
        for line in self.lines:
            line.set_data([], [])
        return self.lines

    def animate(self, i):
        for j,line in enumerate(self.lines):
            line.set_data([0, 2], [10 * j,i]) # some trick to animate fake data.
        return self.lines

app = Grapher()
app.mainloop()
Run Code Online (Sandbox Code Playgroud)

我的猜测是动画循环可能永远不会停止运行,因为只有 tkinter 知道停止?..

注意:我之前制作了一个图表,但我使用 tkinter after() 方法清除和重新创建数据点,但它占用了很多资源,我不得不重新制作它。这样我就不必每秒删除/创建 10-50K 数据点。

tac*_*ell 5


回答错误的问题:

这是按预期运行的(无限循环)。如果您只想运行一次,请使用repeatkwarg (一些神秘的文档):

anim = animation.FuncAnimation(self.fig, self.animate, init_func=self.init,
                               frames=100, interval=1000, blit=True,
                               repeat=False)
Run Code Online (Sandbox Code Playgroud)