1
3

More than 1 year has passed since last update.

[Python] PyAutoGUI 複数画像のどれかが表示されたらクリックする

Last updated at Posted at 2023-02-08

作ったプログラムの備忘録

はじめに

PyAutoGUIにおいて画像認識でクリックさせる場合に、ソフトウェアの前回使用時の設定によって表示される画像が異なる状況が発生したので、複数画像のどれかが表示された場合にクリックできるようにした。

単純な待機処理とクリック処理は以下に記載。

動作テスト環境

OS: Windows 10 Pro 64bit
言語: Python 3.9.13
ライブラリ:PyAutoGUI 0.9.53

ソースコード

import pyautogui
from time import sleep

def plural_search_click(images):
    for i in range(300):
        for img in images:
            try:
                if pyautogui.locateOnScreen(f'./img/{img}', grayscale=True, confidence=.8):
                    get_img = img
                    break
            except pyautogui.ImageNotFoundException:
                pass
        if 'get_img' in locals():
            click_img(get_img, 0.1)
            break
        sleep(0.2)
        
def click_img(img, sleeptime):
    p = pyautogui.locateOnScreen(f'./img/{img}', grayscale=True, confidence=.8)
    x, y = pyautogui.center(p)
    pyautogui.click(x, y, button='left')
    sleep(sleeptime)

plural_search_click(['image01.png', 'image02.png'])
  • PyAutoGUIのlocateOnScreenは1つの画像しか認識できない+try文での例外処理も1つしか補足できないので、for文でlocateOnScreenを複数画像分回して、存在したときだけ変数格納させます。

  • その後if 'get_img' in locals(): で変数が定義されたときだけ、その画像でクリックする関数を呼び出して、待機処理ループを抜けます。

  • ここでは関数の引数として画像のファイル名をリストで渡すようにしています。['image01.png', 'image02.png']

1
3
0

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
3