Tkinter按下按钮以启动动画.py文件

时间:2015-05-01 07:39:38

标签: python animation matplotlib tkinter execfile

原始问题:

我有一个Tkinter按钮,按下后会执行script.py文件。

#-*- coding: utf-8 -*-
from Tkinter import *
master = Tk()
def callback():
    execfile("script.py")
b = Button(master, text="OK", command=callback)
b.pack()
mainloop()

script.py是一个2D动画,它将打开一个动画窗口。

"""
A simple example of an animated plot
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()

x = np.arange(0, 2*np.pi, 0.01)        # x-array
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x+i/10.0))  # update the data
    return line,

#Init only required for blitting to give a clean slate.
def init():
    line.set_ydata(np.ma.array(x, mask=True))
    return line,
ani = animation.FuncAnimation(fig, animate, np.arange(1,200),init_func=init,interval=25, blit=True)
plt.show()

当我运行上面的Tkinter代码并按下按钮来调用动画时,动画将只显示第一帧。换句话说,不会播放动画。但是如果从命令行运行script.py,则动画可以正常播放。问题是,如何从Tkinter代码运行动画播放?

1 个答案:

答案 0 :(得分:0)

我意外地找到了解决这个动画问题的方法,并认为值得写下来。

如果在script.py文件中,我从execfile函数返回一个全局变量,TK按钮的动画回调现在可以正常播放。

from Tkinter import *
master = Tk()
def callback():
    variables= {} #add a variable with witch execfile can return
    execfile("simple_anime.py",    variables)
b = Button(master, text="OK", command=callback)
b.pack()
mainloop()

这样就可以了。而且,我刚才意识到,这就是TigerhawkT3在他的回答中提到的。我查看了子进程,但在这种情况下我仍然不确定如何使用它。