如何将pyautogui独立工具函数封装为类并实现函数间返回值传递
PyAutoGUI工具封装与参数传递解决方案
1. 前置修复:原有函数bug修正
原有代码存在两个影响正常运行的问题,需先修复:
get_screenshoot_coordonate函数定位成功时没有返回坐标值,仅做了打印输出press_key函数返回值拼写错误,Fals需修正为False
2. 零散函数封装为工具类
封装思路:将所有工具方法收拢到同一个操作类中,通过实例属性缓存常用的定位坐标,简化跨方法传参逻辑,同时支持自定义调用规则提升灵活性。
封装后完整代码:
import pyautogui import time class PyAutoGuiTool: def __init__(self): # 缓存最近一次视觉定位得到的坐标 self.last_x = None self.last_y = None def get_screenshot_coordinate(self, src): try: point = pyautogui.locateOnScreen(src) x, y = pyautogui.center(point) print('coordinate : ', x, y) # 缓存坐标到实例属性 self.last_x, self.last_y = x, y # 同时返回坐标供直接调用 return x, y except: print("ERROR screenshot not found") return False def move_click(self, x=None, y=None, use_last=False): # 支持直接传入坐标,或者使用最近缓存的坐标 if use_last and self.last_x is not None and self.last_y is not None: x, y = self.last_x, self.last_y try: pyautogui.click(x=x, y=y, duration=0.5) return True except: return False def write(self, w): try: pyautogui.write(w) return True except: return False def press_key(self, key): try: pyautogui.press(key) return True except: return False def wait(self, seconds): time.sleep(seconds)
3. 跨函数值传递实现
有两种常用的传递方式,均可实现定位坐标传递给点击函数的需求:
- 直接返回值传递:调用定位方法后直接拿到返回的坐标元组,解包后传入点击方法,适合单次使用的场景
示例:tool = PyAutoGuiTool() coord = tool.get_screenshot_coordinate('img/cmd.PNG') if coord: x, y = coord tool.move_click(x, y) - 实例属性缓存传递:定位得到的坐标会自动存入实例属性,点击时直接指定使用最近缓存的坐标即可,适合坐标需要多次复用的场景
示例:tool = PyAutoGuiTool() if tool.get_screenshot_coordinate('img/cmd.PNG'): # 直接使用缓存坐标点击,无需手动传参 tool.move_click(use_last=True)
4. 原业务逻辑改造后的调用示例
# 初始化工具实例 auto_tool = PyAutoGuiTool() auto_tool.move_click(23, 1029) auto_tool.move_click(8, 496) auto_tool.write("cmd") auto_tool.move_click(249, 486) auto_tool.move_click(249, 486) auto_tool.write("ping www.google.ro") auto_tool.press_key('enter') auto_tool.wait(5) auto_tool.move_click(8, 496) # 动态定位并点击cmd窗口 if auto_tool.get_screenshot_coordinate('img/cmd.PNG'): auto_tool.move_click(use_last=True)
内容的提问来源于stack exchange,提问作者cindea sorin
相关产品推荐
相关产品推荐

