无法在Python中更改全局变量的值

时间:2018-08-06 05:33:45

标签: python function global-variables

我有一个函数,我想计算它被调用了多少次(并以该计数器值作为名称保存图像)。我做了一个名为counter的全局函数。但是如果我做counter = counter+1。它说Unresolved reference。我想念什么吗?

这是代码:

import numpy as np
import cv2
counter = 0
def saveImage(img):
    counter = counter+1

    imgs = str(counter) + '.jpg'
    cv2.imwrite('images/'+imgs, img)

1 个答案:

答案 0 :(得分:0)

import numpy as np
import cv2
counter = 0
def saveImage(img):
    global counter  # to modify global variable, you need to explicitly declare so... 
    counter = counter+1

    imgs = str(counter) + '.jpg'
    cv2.imwrite('images/'+imgs, img)