In python, can locateCenterOnScreen be used with region?

Question:

There is a large picture including number 8.

First, I want to detect the large picture as below:

left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3)

Second, if the large picture is detected, then I want to narrow down to find the number 8.

x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))

Finally, I want to click the number 8

pyautogui.click(x, y)

This is my code, but it returns error below:

TypeError: cannot unpack non-iterable NoneType object
import time
import pyautogui

time.sleep(1)
left, top, width, height = pyautogui.locateOnScreen('original.png', confidence=0.3)
if left is None:
    print("Not Detected")
else:
    print("Detected")
    x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
    if x is None:
        print("Error")
    else:
        print("Clicked")
        pyautogui.click(x, y)
Asked By: Jay Jeong

||

Answers:

Yes locateCenterOnScreen can be used with region. That error you get is because pyautogui simply cannot find the object. And since there is no result, it cannot use iteration to assign variables to your x and y

this line here will never be true

if x is None: 

Because this line will throw an error if the object is not found

x, y = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))

To fix your issue, do not force the result on iteration. Assign it to a single variable, then call out each x & y from that variable

Coord = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
if Coord is None:
    print("Error")
else:
    pyautogui.click(Coord.x, Coord.y)
Answered By: Farid Ibrahim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.