【问题标题】:UnboundLocalError: local variable 'xd' referenced before assignmentUnboundLocalError:分配前引用的局部变量“xd”
【发布时间】:2021-07-01 20:09:55
【问题描述】:

这段代码用于制作动画图表。 var xdyd 是 x 轴和 y 轴的数据。所以我通过 +1 对 xd 进行了自动化处理,每 1 秒重复一次使用线程。不幸的是,结果是一个错误:'UnboundLocalError: local variable 'xd' referenced before assignment'。我尝试了很多答案,但有些结果是“定义 xd”或“语法错误”。

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from time import sleep

style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

xd = 0
def animate(i):
    graph_data = open('Example.txt','r').read()
    lines = graph_data.split('\n')
    xs = []
    ys = []
    for line in lines:
        if len(line) > 1:
            x, y  = line.split(',')
            xs.append(float(x))
            ys.append(float(y))

    ax1.clear()
    ax1.plot(xs, ys)

def plotit():
    threading.Timer(1.0, plotit).start()
    xd += 1
    yd = 1
    data = open('/home/pi/Desktop/Real-Time car collision detection/Example.txt','a')
    data.write(str(xd)+','+str(yd))
    data.close()
    //^ This line results with error
plotit()
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()```


【问题讨论】:

标签: python multithreading matplotlib write


【解决方案1】:

在我看来,您想将 xd 定义为全局变量

def plotit():
    global xd
    threading.Timer(1.0, plotit).start()
    xd += 1
    yd = 1
    ...

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    • 2020-09-26
    • 2022-01-02
    • 2019-03-22
    • 2019-01-24
    • 2021-10-16
    相关资源
    最近更新 更多