Use LocateOnScreen with Multiple Monitors
Author: JohnTravolskiCreated Mar 29, 2019Updated Jul 2, 2026
I have an extra monitor plugged into my laptop many times (but not all the time) and I recently noticed that the following code:
import pyautogui
change_intense_to_calm = pyautogui.locateOnScreen('Intense.png', confidence = 0.9)
run_script_button_x, run_script_button_y = pyautogui.center(change_intense_to_calm)
pyautogui.click(run_script_button_x, run_script_button_y)doesn't work when the 'Intense.png" item appears on the second monitor! It does move the mouse to the position and click if it appears on the primary monitor (the laptop screen), but if the window containing that item is on the secondary monitor, it fails, giving me this error:
Traceback (most recent call last):
File "E:\test_folder\switch.py", line 18, in <module>
run_script_button_x, run_script_button_y = pyautogui.center(change_intense_to_calm)
File "C:\Program Files\Python\Python37\lib\site-packages\pyscreeze\__init__.py", line 407, in center
return (coords[0] + int(coords[2] / 2), coords[1] + int(coords[3] / 2))
TypeError: 'NoneType' object is not subscriptablepresumably because it's not finding it.
How can I modify my code so that it will find the item and click it regardless of which monitor the window containing it is located on?
Source: asweigart/pyautogui