我正在尝试通过单击按钮来启动图形(即从串行端口获取数据)。我尝试了以下代码,但没有成功。我是 python 新手。如果我错了,请帮助我指导。
我正在将 Python 2.7 与 Tkinter 一起使用
提前致谢
import serial
import Tkinter as tk
import ttk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import figureCanvasTkAgg
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import tkFileDialog
x = []
adc_data = []
f = plt.Figure(figsize = (9,5), dpi = 100)
ax = f.add_subplot(111)
def select(self):
self.BaudRate = self.Baud.get()
self.COMPort = self.COM.get()
self.ser = serial.Serial(port = self.COMPort, baudrate = self.BaudRate,bytesize = serial.EIGHTBITS, stopbits = serial.STOPBITS_ONE, parity = serial.PARITY_NONE)
self.ser.close()
self.ser.open()
self.ser.flushInput();
self.ser.flushOutput();
def quit_(self):
self.ser.close()
def animate_(i):
self.ser.write(str(chr(250)))
data = self.ser.read(1)
data1 = self.ser.read(1)
LSB = ord(data)
MSB = ord(data1)
x.append(LSB)
adc_data.append(MSB) #adding data to list
plt.pause(.00001)
ax.clear()
ax.plot(x,adc_data)
def animate_button(self):
ani = animation.FuncAnimation(f, animate_,interval=1000)
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 Reference")
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.button = ttk.Button(self, text="Stop", state = 'disable',
command=lambda: quit_(self))
self.button.place(relx = 0.97, rely = 0.95, height = 30 , width = 80, anchor = 'se')
button2 = ttk.Button(self, text="Select",
command = lambda:select(self))
button2.place(relx = 0.97, rely = 0.016, height = 30 , width = 80, anchor = 'ne')
button4 = ttk.Button(self, text="Start",
command=lambda: animate_button(self))
button4.place(relx = 0.03, rely = 0.95, height = 30 , width = 80 , anchor = 'sw')
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().place(relx = 0.5, rely = 0.48, relwidth = 1, relheight = 0.8, anchor = 'center' )
app = ADC_Ref_Data()
app.mainloop()