0

So I keep getting the error: UnboundLocalError: local variable 'old_result' referenced before assignment
and I dont exactly know why. I usually code in javascript, so im new to python but as much as ive figured its because i declare old_result in the function again, but I would like to make it global and just change its value in the function. Anyway I can fix this?

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()
WiHa
  • 35
  • 2
  • 4

2 Answers2

0

If you are modifying the value of global variable inside the function you have to declare it as a global in it. If you are not modifying the value of the global variable then you can declare it as a global or not it will refer to the global variable copy only.

So you have to add one line of code inside the function before you are accessing the global variable. So your updated code is as below:

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)

    global old_result  # Add this line in your function
    if new_result < old_result:
        print("play da music")
        old_result = new_result


ocrit()
Rahul Talole
  • 137
  • 1
  • 2
  • 9
0

In the function, declare:

global old_result
Mario Camilleri
  • 1,457
  • 11
  • 24