在Tkinter中嵌入动画Matplotlib导致程序永无休止

时间:2019-01-03 20:05:55

标签: python user-interface matplotlib tkinter

我进行了搜索,无法找到关闭窗口后如何结束该程序的方法。它适用于静态pyplot,但运行动画图时,当我关闭窗口时,必须使用fn-ctrl-b退出程序。

#---------Imports
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import time
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#---------End of imports

# Create figure for plotting
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
xs = []
ys = []
zs = []

def animate(i, xs, ys, zs):
    xs.append(time.clock())
    ys.append(time.clock()+np.random.random())

    xs = xs[-100:]
    ys = ys[-100:]

    ax.clear()
    ax.plot(xs, ys)

root = tk.Tk()

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

ani = animation.FuncAnimation(fig, animate, fargs=(xs, ys, zs), interval=5)

tk.mainloop()

我先感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

我的回答将在OOP中。我更喜欢使用类方法。

ImportanceOfBeingErnest指出pyplot可能是罪魁祸首,因此我们应在此处使用matplotlib中的figure

使用从matplotlib而不是pyplot导入图形后,我发现我注意到的任何问题现在都消失了。这应该可以解决您的问题。

import tkinter as tk
import numpy as np
import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import animation, figure


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        fig = figure.Figure()
        canvas = FigureCanvasTkAgg(fig, master=self)
        canvas.get_tk_widget().grid(column=0, row=0)
        self.ax = fig.add_subplot(1, 1, 1)
        self.xs = []
        self.ys = []
        self.zs = []

        self.ani = animation.FuncAnimation(fig, self.animate, interval=5)

    def animate(self, event):
        self.xs.append(time.clock())
        self.ys.append(time.clock() + np.random.random())
        self.xs = self.xs[-100:]
        self.ys = self.ys[-100:]
        self.ax.clear()
        self.ax.plot(self.xs, self.ys)


if __name__ == "__main__":
    App().mainloop()