[英]Tkinter press a button to launch an animation .py file
原始问题:
我有一个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代码运行时如何制作动画播放?
我无法重现您遇到的行为,初始化中断了。
File "script.py", line 19, in init
line.set_ydata(np.ma.array(x, mask=True))
但是,您可以重新设计应用程序,以依靠更常规的import
来执行另一个文件中的python代码。 您可以通过这种方式更改script.py
#script.py
def script():
#previous script.py content
if __name__ == '__main__':
script()
这样,如果您运行文件,则匹配 __name__ == '__main__'
子句,您的文件将独立运行。 导入时, script
函数将被定义但不会执行。 在您的tkinter程序中,您只需要
import script
def callback():
script.script()
我出乎意料地找到了解决此动画问题的方法,并认为值得写下来。
如果在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在他的回答中提到的内容。 我研究了子流程,但仍不确定在这种情况下如何使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.