【发布时间】:2016-01-08 10:05:00
【问题描述】:
我已经使用 tkinter 和 pyhton2.7 构建了一个 GUI,我已经成功地在我的 GUI 中绘制来自我的串行端口的数据(使用 Matplotlib)。我的代码快照如下:
""All required import was done here""
x = []
adc_data = []
q = [0]
f = plt.Figure(figsize = (9,5), dpi = 100)
ax = f.add_subplot(111)
class ADC_Ref_Data(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_geometry(self, '900x600+200+150')
tk.Tk.wm_title(self, "ADC Referene")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
frame = StartPage(container, self)
self.frames[StartPage] = frame
frame.grid(row=0, column=0, sticky = "nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.button4 = ttk.Button(self, text="Start",
command=lambda: self.start())
self.button4.place(relx = 0.03, rely = 0.95, height = 30 , width = 80 , anchor = 'sw')
self.canvas = FigureCanvasTkAgg(f, self)
self.canvas.show()
self.canvas.get_tk_widget().place(relx = 0.5, rely = 0.48, relwidth = 1, relheight = 0.8, anchor = 'center' )
def animate(self,i):
while self.button4['text'] == 'Pause':
self.ser.write(str(chr(250)))
data = self.ser.read(1)
data1 = self.ser.read(1)
LSB = ord(data)
MSB = ord(data1)
dec = 256*MSB+LSB
q[0] = q[0]+1
x.append(q[0]) #adding data to list
adc_data.append(dec) #adding data to list
plt.pause(1)
ax.clear()
a = ax.plot(x,adc_data,'^r')
def start(self):
if self.button4['text'] == 'Start':
ani = animation.FuncAnimation(f, self.animate,init_func=self.init,frames = 10, interval=1000)#,blit = True)
f.canvas.show()
app = ADC_Ref_Data()
app.mainloop()
从上面的代码中你可以看到,每当我按下我的 Gui 上的开始按钮时,它都会调用一个函数“Start”,在该函数中调用 Funcanimation 并连续绘制一个图形(在无限循环中)。现在我想在按下停止按钮时停止这个 Funcanimation。
如何停止正在运行的 Funcanimation?
请帮我解决这个问题。
提前致谢
【问题讨论】:
-
animate()应该只返回新数据,ani应该使用这些数据来绘制新的动画帧。现在你在animate()中使用while并且你自己做所有动画 - 这样你就不需要FuncAnimation -
您可以使用
ani.repeat = False停止重复动画,但我认为您的animate()函数不正确 - 它应该得到新的数据结束返回adc_data。FuncAnimation获取此数据,清除绘图,绘制新数据,暂停,然后再次调用animate()获取新数据。
标签: python-2.7 matplotlib tkinter