错误:“分配前已引用本地变量'myData'”

问题描述 投票:0回答:1

晚上好,

我是python的新手。在尝试开发来自LIDAR传感器的实时图形绘图数据时,我正在完成一个教程。我收到错误消息“ UnboundLocalError:分配前已引用本地变量'myData'”有人知道如何解决此问题吗?

import pyqtgraph as pg
import sys  # We need sys so that we can pass argv to QApplication
import os
import serial
import csv
import numpy as np
from datetime import datetime
from matplotlib import pyplot as plt
from matplotlib import style
from PyQt5 import QtWidgets, uic, QtCore
from pyqtgraph import PlotWidget, plot

arduinoSerialData = serial.Serial('com3', 9600)
NameofCSV = 'data2.csv'
style.use('ggplot')

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.graphWidget = pg.PlotWidget()
        self.setCentralWidget(self.graphWidget)

        if (arduinoSerialData.inWaiting()>0):
            myData = arduinoSerialData.readline()
            xn = datetime.now()
            Time = xn.strftime('%H%M%S')

        with open(NameofCSV, 'a', newline='') as csvfile:
            writer = csv.writer(csvfile, delimiter=' ')

            info = (float(myData), float(Time))
            writer.writerow(info)

            # print(float(myData), Time)
            x1,y1 = np.loadtxt(NameofCSV, unpack = True, delimiter = ' ')

        self.x = x1
        self.y = y1  

        self.graphWidget.setBackground('w')

        pen = pg.mkPen(color=(255, 0, 0))
        self.data_line =  self.graphWidget.plot(self.y, self.x, pen=pen)
                # ... init continued ...
        self.timer = QtCore.QTimer()
        self.timer.setInterval(50)
        self.timer.timeout.connect(self.update_plot_data)
        self.timer.start()

    def update_plot_data(self):

        self.x = self.x[1:]  # Remove the first y element.
        self.x.append(self.x[-1] + 1)  # Add a new value 1 higher than the last.

        self.y = self.y[1:]  # Remove the first 
        self.y.append(self.y)  # Add a new random value.

        self.data_line.setData(self.x, self.y)  # Update the data.

app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

python-3.x matplotlib pyqtgraph
1个回答
0
投票

因此,myData仅在此块中初始化:

if (arduinoSerialData.inWaiting()>0):
            myData = arduinoSerialData.readline()

如果if子句的计算结果不为True,它将跳过它,稍后您将使用myData而不进行初始化:info = (float(myData), float(Time))

您可以在顶部将myData初始化为某个初始值,或者确保在使用它的值之前始终运行将其设置为值的代码。

快乐编码!

© www.soinside.com 2019 - 2024. All rights reserved.