我尝试了几个不同的东西来停止这些代码(在[不停止]之后,退出[关闭GUI])。我发现"工作"它是在抛出一个错误......这让我很困扰。抛出错误,然后重新启动图表并不理想。我想清理这段代码(所以其他任何建议也都很受欢迎!)
我错过了什么吗?不能停止功能很简单吗?我将发布主要代码,因为有很多功能,所以仍然很多。我要停止的两个(根据打印出来的)是update_graph和get_data。如果我说我需要5个文件,它会获得5个文件(i = 5),然后重新启动0(i = 0)。
代码应该执行的操作:
首先,它在GUI上显示一个空白图表。 Person可以设置他们希望拥有的文件数量并设置传感器集成时间。然后,他们可以开始数据采集,图表每隔一秒左右弹出一次,直到达到文件数。最后一部分是我无法得到的。达到文件数时停止文件创建和图形。 (注意:文件创建在另一个代码中是完美的。我只显示此代码,以便我不会创建大量文件来解决此问题。)
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
from PIL import ImageTk, Image
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import serial
import random
import os
import datetime
import numpy as np
after_id = None
def get_data():
#i=0
rand_x = list(range(100))
rand_y = [random.randrange(100) for _ in range(100)]
#create a file
## In my code, this function send data through serial port from the Raspberry pi to the arduino and the arduino send the y axis data back.
##I then create the appropriate x axis
return rand_x, rand_y
class App(tk.Frame):
def __init__ (self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.running = False
self.ani = None
btns = tk.Frame(self)
btns.pack()
lbl = tk.Label(btns, text="Number of times to run")
lbl.pack(side=tk.LEFT)
self.points_ent = tk.Entry(btns, width=5)
self.points_ent.insert(0,'50')
self.points_ent.pack(side=tk.LEFT)
lbl = tk.Label(btns, text="Intergration Time")
lbl.pack(side=tk.LEFT)
self.interval = tk.Entry(btns, width=5)
self.interval.insert(0, '100')
self.interval.pack(side=tk.LEFT)
self.btn = tk.Button(btns, text='Start', command=self.on_click)
self.btn.pack(side=tk.LEFT)
self.fig = plt.Figure()
self.ax1 = self.fig.add_subplot(111)
self.line, = self.ax1.plot([], [], lw=2)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.show()
self.canvas.get_tk_widget().pack()
self.ax1.set_ylim(0, 500)
self.ax1.set_xlim(0, 100)
def on_click(self):
print('onclick')
if self.ani is None:
return self.start()
if self.running:
self.ani.event_source.stop()
self.btn.config(text='Un-Pause')
print('pause')
else:
self.ani.event_source.start()
self.btn.config(text='Pause', command=get_data())
print('unpause')
self.running = not self.running
def start(self):
global interval
self.points = int(self.points_ent.get()) + 1
print(self.points)
self.ani = animation.FuncAnimation(
self.fig, self.update_graph,
frames=self.points,
interval=int(self.interval.get()),
repeat=True)
self.running = True
self.btn.config(text='Pause')
self.ani._start()
print('started animation')
def update_graph(self, i):
while os.path.exists(str(directory) + "/Data" + str(i) + "/"):
i +=1
subfolder = (str(directory) + "/Data" + str(i) + "/")
global filename
filename = "/home/pi/Documents/Serial" + str(i) + ".txt"
self.line.set_data(*get_data())
print('update_graph')
print(i)
global after_id
after_id = self.after(1, get_data)
if i >= self.points - 1:
self.running = False
self.ani = None
self.btn.config(text='Start', command=self.stop())
def stop(self):
global after_id
self.after_cancel(after_id)
答案 0 :(得分:1)
我认为您在update_graph
函数中遗漏了一条非常重要的声明,并尝试使用after
并更改按钮命令以尝试修复它。
update_graph
中您遗漏的内容只是self.ani._stop()
,以便在满足所需的迭代次数时停止动画。
所以把它放进去,并删除我认为没有任何好处的所有after
电话,只留下按钮命令,我觉得这就是你想要的:
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import matplotlib.animation as animation
import random
def get_data():
#i=0
rand_x = list(range(100))
rand_y = [random.randrange(100) for _ in range(100)]
#create a file
## In my code, this function send data through serial port from the Raspberry pi to the arduino and the arduino send the y axis data back.
##I then create the appropriate x axis
return rand_x, rand_y
class App(tk.Frame):
def __init__ (self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.running = False
self.ani = None
btns = tk.Frame(self)
btns.pack()
lbl = tk.Label(btns, text="Number of times to run")
lbl.pack(side=tk.LEFT)
self.points_ent = tk.Entry(btns, width=5)
self.points_ent.insert(0,'50')
self.points_ent.pack(side=tk.LEFT)
lbl = tk.Label(btns, text="Intergration Time")
lbl.pack(side=tk.LEFT)
self.interval = tk.Entry(btns, width=5)
self.interval.insert(0, '100')
self.interval.pack(side=tk.LEFT)
self.btn = tk.Button(btns, text='Start', command=self.on_click)
self.btn.pack(side=tk.LEFT)
self.fig = plt.Figure()
self.ax1 = self.fig.add_subplot(111)
self.line, = self.ax1.plot([], [], lw=2)
self.canvas = FigureCanvasTkAgg(self.fig, master=self)
self.canvas.show()
self.canvas.get_tk_widget().pack()
self.ax1.set_ylim(0, 500)
self.ax1.set_xlim(0, 100)
def on_click(self):
print('onclick')
if self.ani is None:
return self.start()
if self.running:
self.ani.event_source.stop()
self.btn.config(text='Un-Pause')
print('pause')
else:
self.ani.event_source.start()
self.btn.config(text='Pause')
print('unpause')
self.running = not self.running
def start(self):
self.points = int(self.points_ent.get()) + 1
print(self.points)
self.ani = animation.FuncAnimation(
self.fig, self.update_graph,
frames=self.points,
interval=int(self.interval.get()),
repeat=True)
self.running = True
self.btn.config(text='Pause')
self.ani._start()
print('started animation')
def update_graph(self, i):
self.line.set_data(*get_data())
print('update_graph')
print(i)
if i >= self.points - 1:
self.running = False
self.ani._stop()
self.ani = None
self.btn.config(text='Start')
root = tk.Tk()
app = App(root)
app.pack(expand=1, fill=tk.BOTH)
root.mainloop()