Search code examples
pythonpyautogui

I can't find an example of pyautogui.locateOnWindow


I am trying to locate the cordinates of an image with locateOnWindow()

position = pt.locateOnWindow(image, 'Discord', grayscale=True, confidence=.9)

I get this error and the discord window icon turns into orange. Picture

raise PyGetWindowException('Error code from Windows: %s - %s' % (errorCode, _formatMessage(errorCode))) pygetwindow.PyGetWindowException: Error code from Windows: 0 - The operation completed successfully.


Solution

  • From pyautogui documentation, as Screenshot Functions says: you can call the locateOnScreen() function to get the screen coordinates. The return value is a 4-integer tuple: (left, top, width, height). This tuple can be passed to center() function to get the X and Y coordinates at the center of this region.

    So I saved a discord icon image from my laptop and found the coordinates correctly as below:

    Image:

    Discord

    import pyautogui
    
    image = 'discord.png'
    
    locate = pyautogui.locateOnScreen(image, grayscale=True, confidence=0.8)
    
    position = pyautogui.center(pyautogui.locateOnScreen(image, grayscale=True, confidence=0.8))
    

    If you print(locate):

    Box(left=91, top=288, width=23, height=26)
    

    If you print(position):

    Point(x=102, y=301)