Skip to content

Fix pyautogui.click('button.png') so documented image-path usage works#950

Open
AbhisumatK wants to merge 1 commit intoasweigart:masterfrom
AbhisumatK:fix-click-image-path
Open

Fix pyautogui.click('button.png') so documented image-path usage works#950
AbhisumatK wants to merge 1 commit intoasweigart:masterfrom
AbhisumatK:fix-click-image-path

Conversation

@AbhisumatK
Copy link

The docs show click('button.png') to find an image on screen and click
its center, but this could fail with TypeError when the image wasn't
found because _normalizeXYArgs returned None and callers unpacked it.

  • In _normalizeXYArgs, when an image path is given and locateOnScreen
    returns None, raise ImageNotFoundException instead of returning None,
    so click() and other callers never receive None.
  • Remove unreachable return after the except block.
  • Update test to expect ImageNotFoundException when image path is given
    and image not found, using a mock so the test doesn't depend on screen.

Root cause

For an image path (string), _normalizeXYArgs() calls locateOnScreen(path). When the image wasn’t found, locateOnScreen returned None (with the default pyscreeze setting), and _normalizeXYArgs returned None. Callers like click() then did x, y = _normalizeXYArgs(x, y) and crashed with TypeError, so the documented “click by image” behavior never succeeded in the failure case and looked broken overall.

Approach

  1. Fix in _normalizeXYArgs
    When firstArg is a string (image path) and locateOnScreen(firstArg) returns None, raise ImageNotFoundException instead of returning None. That way callers always get either a valid Point or a clear exception, and the documented click('button.png') flow can work when the image is found.

  2. Cleanup
    Removed the unreachable return center(locateOnScreen(firstArg)) after the except block in the string branch.

  3. Tests
    Updated the _normalizeXYArgs test so that when an image path is given and the image is not found, ImageNotFoundException is expected (for both useImageNotFoundException(True) and False), and used a mock for locateOnScreen so the test doesn’t depend on screen content.

Result

  • Image found: pyautogui.click('button.png') works as documented: the image is located and its center is clicked.
  • Image not found: A clear ImageNotFoundException is raised instead of a TypeError, so the documented syntax is fully supported and failures are handled correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant