如何在进行处理/其他工作时确保FuncAnimation在tkinter中顺利运行?

时间:2016-10-26 03:16:01

标签: python animation matplotlib tkinter

我正在尝试使用tkinter和matplotlib创建一个实时情节。事情是,动画片可能会做一些“沉重的”#34;每次调用动画时,工作量都足够大,可以稍微冻结tkinter窗口。为简单起见,我在tkinter窗口内创建了一个简单的图。

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

fig = plt.Figure()

x = np.arange(0, 2*np.pi, 0.01)


def animate(i):
    for j in range(10000000):
        k=j
    line.set_ydata(np.sin(x + i / 10.0))
    return line

root = Tk.Tk()

label = Tk.Label(root, text="Graph")
label.grid(column=0, row=0)

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

ax = fig.add_subplot(111)
line, = ax.plot(x, np.sin(x))

ani = animation.FuncAnimation(fig, animate, np.arange(1, 200), interval=250, blit=False)

Tk.mainloop()

如果您运行代码并尝试移动窗口,每次调用动画时都会发现轻微冻结。请注意,这不是我的项目的实际代码,只是过度简化。我已经把for循环模拟为animate函数可能正在做的繁重工作。

那么,有没有办法让动画与tkinter主循环分开运行?我试图为动画创建一个不同的线程,但我无法让它工作。任何帮助,将不胜感激。谢谢!

0 个答案:

没有答案