Search code examples
pythonpython-3.xcoordinatespyautogui

My PyAutoGUI script is raising TypeError: 'NoneType' object is not subscriptable after calling locateOnScreen()


I wrote a python program that takes a screenshot and looks for a .PNG image in the given region and clicks on that picture if it's there. I am using the library pyautogui.

while keyboard.is_pressed('q') == False:

    pic = pyautogui.screenshot(region=(360,158,1900,1025))

    width, height = pic.size

    if pyautogui.locateOnScreen('greenlightning.png', region=(360,158,1900,1025), grayscale=True, confidence=0.8) != None:
        lightningloc = pyautogui.locateOnScreen('greenlightning.png')
        x = lightningloc[0]
        y = lightningloc[1]
        pyautogui.click(x, y - 50)
        time.sleep(0.2)
    else:
        time.sleep(0.1)

The problem is that it sometimes throws me a TypeError because "x" or "y" is 'NoneType'.

  File "C:\****\**\***\***\****.py", line 18, in <module>
    x = lightningloc[0] TypeError: 'NoneType' object is not subscriptable

I just want the program to click on a pixel that is 50 pixels higher than the coordinates of my image 'greenlightning.png'. Do you have any idea about the pyautogui.click() function?


Solution

  • I think the problem is the first locateOnScreen() call returns coordinates but the second call returns None. The [0] in lightningloc[0] is called a subscript. The error message is telling you that you tried to subscript a value of NoneType. lightningloc is the variable being subscripted. None is the only value with a type of NoneType, so lightningloc is None. Try calling locateOnScreen() once and assign it to a variable and then check for None, like this:

        lightningloc = pyautogui.locateOnScreen('greenlightning.png', region=(360,158,1900,1025), grayscale=True, confidence=0.8)
        if lightningloc is not None:
            x = lightningloc[0]
            y = lightningloc[1]
            pyautogui.click(x, y - 50)
            time.sleep(0.2)
        else:
            time.sleep(0.1)