LoginSignup
1
2

More than 3 years have passed since last update.

MacBook ProでPyAutoGUIの座標が正しく取れない?

Last updated at Posted at 2020-12-28

動かない

Python + PyAutoGUIでMacBook Pro(15-inch, 2018)のDockにあるアイコンをクリックさせようと、こんなコードを書いたら動かなかった。

click.py
import pyautogui as pag

position = pag.locateCenterOnScreen('target_app.png', confidence=0.9)
pag.click(position)

※target_app.pngはDockのアイコンをスクリーンショットした画像

Dockが一瞬だけピクッと動いて、ターゲットのアプリケーションが起動しない。

Dockのアイコン位置の座標を調べたところ、locateCenterOnScreenで取得した値と、アイコンにマウスを当ててposition()で取得した値がぜんぜん違うことに気づいた。

locateCenterOnScreenで取得した値
 x=3046, y=2335 

pyautogui.position()で取得したマウスカーソルの値
 x=1517, y=1169 

Retinaディスプレイの解像度が関係している?

xもyも半分くらいの値なのでRetinaディスプレイの解像度が関係しているのかと思い、それぞれを2分の1にした値をclick()に渡してみた。

click.py
import pyautogui as pag

x,y = pag.locateCenterOnScreen('target_app.png', confidence=0.9)
pag.click(x/2, y/2)

ビンゴ。
これでDock上のアイコンをクリックしてアプリケーションを起動することができた。

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2