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

时间:2015-04-19 18:03:32

标签: python matplotlib

我已经在tkinter中运行了这个matplotlib动画,它工作正常,但是当我按下X' 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()

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

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

1 个答案:

答案 0 :(得分:1)


回答错误的问题:

这表现得如预期(无限循环)。如果您只想运行一次,请使用repeat kwarg(some what arcane docs):

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