首页 > 解决方案 > 带有全局变量和局部变量声明的python错误,在声明后更改变量值

问题描述

所以我不断收到错误:UnboundLocalError: local variable 'old_result' referenced before assignment
,我不知道为什么。我通常用 javascript 编写代码,所以我是 python 的新手,但我认为它是因为我再次在函数中声明 old_result,但我想让它成为全局的,只是在函数中更改它的值。无论如何我可以解决这个问题?

from PIL import Image, ImageGrab
import pytesseract
import threading
import winsound


old_result = 100

def ocrit():
    threading.Timer(5.0, ocrit).start()
    img = ImageGrab.grab(bbox=(110,70,250,200))
    result = pytesseract.image_to_string(img, 
    lang='eng')
    print(result)
    new_result = int(result)

    if new_result < old_result:
        print("play da music")
        old_result = new_result


ocrit()

标签: python

解决方案


在函数中,声明:

global old_result

推荐阅读