[英]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.