我坚持我的代码。我想让pyqt5上的图形用户界面显示我的图形。我有Matplot中的工作代码,但无法将其转换为Pyqt。我是个初学者。我试图找到类似的代码,但我只做了这个。这在Matplotlib上有效,但我想在我的GUI上使用它。
import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *
distance =[]
arduinoData=serial.Serial('COM4',115200)
plt.ion()
cnt=0
def makeFig():
plt.ylim(2,20)
plt.title('Plot ')
plt.grid(True)
plt.ylabel('Distance cm')
plt.plot(distance, 'ro-', label='Distance ')
plt.legend(loc='upper left')
while True: # While loop that loops forever
while (arduinoData.inWaiting()==0): #Wait here until there is data
pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from the serial port
measurement = int(arduinoString) #Convert first element to floating number and put in measurement
distance.append(measurement) #Build our distance array by appending temp readings
drawnow(makeFig) #Call drawnow to update our live graph
plt.pause(.000001) #Pause Briefly. Important to keep drawnow from crashing
cnt=cnt+1
if(cnt>50): #If you have 50 or more points, delete the first one from the array
distance.pop(0) #This allows us to just see the last 50 data points
#This allows us to just see the last 50 data points
我的Pyqt和Matplot。我想点击按钮并显示这个图表。
我的错误是“在第51行,在情节中
测量=int(Arduinostring)
valueError:以10为基的int()的文本无效:b'\n'',并且
“后端tkagg是交互式后端。打开交互模式。“
我发送的数据距离我的传感器很简单,比如5、10等等。
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
import serial
import numpy
from drawnow import *
arduinoData=serial.Serial('COM4',115200)
cnt=0
distance =[]
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
while True:
while (arduinoData.inWaiting()==0): #wait for data
pass
arduinoString=arduinoData.readline() #read the line of text from the serial port
measurement=int(arduinoString)
distance.append(measurement)
plt.pause(0.00001)
global cnt
cnt=cnt+1
if (cnt>50):
distance.pop(0)
self.figure.clear()
ax = self.figure.add_subplot(111)
ax.plot(distance, '*-')
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())