pyautogui

hziwei發表於2024-04-01
from typing import Tuple

import pyperclip
import pyautogui
import cv2
import numpy as np


class Gui(object):
    '''
    pyautogui 操作
    '''

    @classmethod
    def find_img_position_yn(cls, file_path: str) -> (int, int):
        '''
        查詢圖片位置
        :param file_path: 檔案路徑
        :return: 返回是否查到
        '''
        target_image = cv2.imread(file_path)
        screenshot = pyautogui.screenshot()
        screenshot = np.array(screenshot)
        screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
        result = cv2.matchTemplate(screenshot, target_image, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, max_loc = cv2.minMaxLoc(result)
        if max_val > 0.9:
            return True
        else:
            return False

    @classmethod
    def find_img_position(cls, file_path: str) -> (int, int):
        '''
        查詢圖片位置
        :param file_path: 檔案路徑
        :return: 返回座標
        '''
        target_image = cv2.imread(file_path)
        screenshot = pyautogui.screenshot()
        screenshot = np.array(screenshot)
        screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR)
        result = cv2.matchTemplate(screenshot, target_image, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, max_loc = cv2.minMaxLoc(result)
        target_center = (max_loc[0] + target_image.shape[1] // 2, max_loc[1] + target_image.shape[0] // 2)
        return target_center

    @classmethod
    def click(cls, position: Tuple[int, int]):
        return pyautogui.click(position)

    @classmethod
    def hotkey(cls, *args, **kwargs):
        return pyautogui.hotkey(args, kwargs)
        pass

    @classmethod
    def delete(cls):
        return pyautogui.press('delete')

    @classmethod
    def enter(cls):
        return pyautogui.press('enter')

    @classmethod
    def copy(cls, text: str):
        return pyperclip.copy(text)

    '''pyautogui.hotkey('ctrl', 'a')
    pyautogui.press('delete')'''
    pass