Search code examples
pythonautomationpyautogui

How can I make pyautogui tell me the coordinates of the locateOnScreen function


My goal for this right now is to be able to receive the coordinates from the pyautogui function locateOnScreen and use the returned coordinates to click an object on the screen. I know how to use coordinates to click on screen but I cannot find the coordinates from the locateOnScreen function

Code

This is what I have so far which finds an object on the screen and determines if the object is visible. I just need to grab the coordinates of the object.

from pyautogui import *
import pyautogui
import time
import keyboard
import random

while True:
    if pyautogui.locateOnScreen('x1.png', confidence=0.9) is not None:
        print("I can see it")
        time.sleep(1)
    else:
        print("I can not see the X")
        time.sleep(2)

x1.png

x1.png


Solution

  • See the documentation: The return value of the locateOnScreen function holds the coordinates.

    x1_coordinates = pyautogui.locateOnScreen('x1.png', confidence=0.9)
    print(x1_coordinates)  # This will print out where it is
    
    if x1_coordinates:
        print(f"I can see it at {x1_coordinates}")
    else:
        print("I cannot see it.")
    

    UPDATE: In chat, we've also discussed clicking on that object. For that, you can use locateCenterOnSCreen or pyautogui.click(x.left + 3, x.top - 3) (which is a bit of a hack and I wouldn't recommend using it).