【python】错误:UnboundLocalError: local variable 'XXX' referenced before assignment

1、错误:UnboundLocalError: local variable 'XXX' referenced before assignment

错误: UnboundLocalError:在赋值之前引用了局部变量“XXX”

例: 

def test():
    i=i+1
    print("global i = ",i)

i=0
test()

报错: 

 【python】错误:UnboundLocalError: local variable 'XXX' referenced before assignment_第1张图片

原因:在函数外部定义变量,在函数内部对变量进行赋值,解释器无法辨别该变量是局部变量还是全局变量 

修改:

def test():
    global i
    i=i+1
    print("global i = ",i)

i=0
test()

成功运行:

2、例:opencv 鼠标事件——框选图像、保存图像

import cv2

def draw_rectangle(event,x,y,flags,param):
    global ix, iy
    global i          #保存图像数
    if event==cv2.EVENT_LBUTTONDOWN:
        ix, iy = x, y #起点
        print("起点point:=", x, y)
        
    elif event==cv2.EVENT_LBUTTONUP:
        print("终点point:=", x, y)
        print("宽度width=",x-ix)                                 #宽度
        print("高度height=", y - iy)                             #高度
        cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 2)    #框选矩形
        cv2.imwrite("image_%d.jpg"%i,img)                       #文件名
        i=i+1

i=0
img = cv2.imread("D:/Sublime Text 3/Opencv_Program/body_detection/TKinter/people_faces.jpg")  #加载图片
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_rectangle)
while(1):
    cv2.imshow('image', img)
    if cv2.waitKey(20) & 0xFF == 27:
        break
cv2.destroyAllWindows()

 

你可能感兴趣的:(Python,local,varia)