from PIL import Image, ImageGrab import os import time import win32api import win32con from ctypes import *
class ImageMatch: # 定义键盘常用按钮,用于文本框的输入操作 VK_CODE = { 'backspace': 0x08, 'tab': 0x09, 'enter': 0x0D, 'left_arrow': 0x25, 'up_arrow': 0x26, 'right_arrow': 0x27, 'down_arrow': 0x28, '0': 0x30, '1': 0x31, '2': 0x32, '3': 0x33, '4': 0x34, '5': 0x35, '6': 0x36, '7': 0x37, '8': 0x38, '9': 0x39, 'a': 0x41, 'b': 0x42, 'c': 0x43, 'd': 0x44, 'e': 0x45, 'f': 0x46, 'g': 0x47, 'h': 0x48, 'i': 0x49, 'j': 0x4A, 'k': 0x4B, 'l': 0x4C, 'm': 0x4D, 'n': 0x4E, 'o': 0x4F, 'p': 0x50, 'q': 0x51, 'r': 0x52, 's': 0x53, 't': 0x54, 'u': 0x55, 'v': 0x56, 'w': 0x57, 'x': 0x58, 'y': 0x59, 'z': 0x5A }
# 启动一个应用程序 def start_app(self, cmd): # start /b 命令的目的是让程序在后台运行,不阻塞当前程序的运行主线程 os.system("start /b " + cmd) time.sleep(3)
# 移动到对象所在位置并实现单击操作 def click(self, target): x, y = self.find_image(target) # 查找模板图片的中心点位置 windll.user32.SetCursorPos(x, y) #将光标移动到指定位置 # 实现鼠标左键的点击操作(按下,弹起两步操作) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) # 双击操作 def double_click(self, target): x, y = self.find_image(target) windll.user32.SetCursorPos(x, y) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0)
# 在文本框中输入内容 def input(self, target, content): self.double_click(target) # 先双击选择文本框中已有内容(没有也不影响) # 再点击回退键将已有内容删除 win32api.keybd_event(self.VK_CODE['backspace'], 0, 0, 0) win32api.keybd_event(self.VK_CODE['backspace'], 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(1)
# 根据输入的字符串内容遍历每一个字符,将其输入(从VK_CODE字典中获取) for c in content: win32api.keybd_event(self.VK_CODE[c], 0, 0, 0) win32api.keybd_event(self.VK_CODE[c], 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.1) # 下拉框的选择,使用下箭头按键次数来决定选择哪一条 def select(self, target, count): self.click(target) time.sleep(0.5) for i in range(count): win32api.keybd_event(self.VK_CODE['down_arrow'], 0, 0, 0) win32api.keybd_event(self.VK_CODE['down_arrow'], 0, win32con.KEYEVENTF_KEYUP, 0) time.sleep(0.5) win32api.keybd_event(self.VK_CODE['enter'], 0, 0, 0) win32api.keybd_event(self.VK_CODE['enter'], 0, win32con.KEYEVENTF_KEYUP, 0) |