我有一个串行端口,每秒接收一个数据点。在
现在我想使用一个带有TkInter的GUI,它包含matplotlib中的一个图形,它实时地绘制接收到的数据点。同时我仍然 想用图形用户界面来执行其他基本的事情,比如输入和按钮来计算过去的数据点等等
我想知道什么是最有效的方法来更新绘图,同时每秒监听串行端口,同时仍然允许GUI和Python程序在后台完美地工作。在
我在考虑使用函数,并在mainloop中每秒调用一个getSerialData函数,但由于我是Python新手,我不知道这个结构是如何工作的,如果你们能给我一个简短的大纲,我应该如何将它嵌入主代码中。在
谢谢!在
编辑2:好的,我开始工作了。但看起来很乱,有没有更好的方法呢?我不喜欢所有这些不同的对象和自我,还是所有这些都是必要的?在
from tkinter import *
import serial
class SerialImport:
def __init__(self, master): #master imports the root window
self.printButton = Button(text="Test GUI response", command=self.printMessage)
self.printButton.grid(row=0)
self.openButton = Button(text="Open Serial Port", command=self.openPort)
self.openButton.grid(row=1)
self.closeButton = Button(text="Close Serial Port", command=self.closePort)
self.closeButton.grid(row=2)
self.updateButton = Button(text="Read and Print Data", command=self.update)
self.updateButton.grid(row=3)
def printMessage(self):
print("GUI does respond!")
def openPort(self):
self.arduinoSerialData = serial.Serial('com3', 9600)
def closePort(self):
self.arduinoSerialData.close()
def update(self):
while(1==1):
if (self.arduinoSerialData.inWaiting()>0):
myData = self.arduinoSerialData.readline()
self.temperature = float(myData)
print(self.temperature)
root.after(1000, self.update)
break
root = Tk()
s = SerialImport(root) #root gets treated as master in SerialImport class
root.mainloop()
目前没有回答
相关问题 更多 >
编程相关推荐