1

使用python控制Qt程序,进行文本输入,按钮点击等组件控制

方法一

思路:使用pywin32获取窗口句柄,获取窗口位置,根据组件相对定位与窗口定位得到组件绝对定位,模拟鼠标按下,键盘输入即可

安装

pip install pywin32

源码

import pyautogui
import win32api
import win32gui
import pyperclip


def findWindow(title):
    windows = pyautogui.getWindowsWithTitle(title)
    if(len(windows) == 0):
        raise Exception("未找到窗口")
    return windows[0]

def PushButtonClick(hwd,relatePos):
    # 模拟按钮点击
    curPosi = win32api.GetCursorPos()

    hwdPosi = win32gui.GetWindowRect(hwd)

    win32api.SetCursorPos([hwdPosi[0]+relatePos[0],hwdPosi[1]+relatePos[1]])

    pyautogui.click()

    pyautogui.sleep(0.3)

    win32api.SetCursorPos(curPosi)

def LineEditInput(hwd,relatePos,value):
    # 模拟输入框输入
    curPosi = win32api.GetCursorPos()

    hwdPosi = win32gui.GetWindowRect(hwd)

    win32api.SetCursorPos([hwdPosi[0] + relatePos[0], hwdPosi[1] + relatePos[1]])

    pyautogui.click()

    pyperclip.copy(value)

    pyautogui.hotkey('ctrl','v')

    pyautogui.sleep(0.3)

    win32api.SetCursorPos(curPosi)

def main():

    hwd = win32gui.FindWindow(None,"Test")

    win32gui.SetForegroundWindow(hwd)

    LineEditInput(hwd, [140, 70], "测试")
    PushButtonClick(hwd,[300,70])


main()

效果图

1.gif

方法二

思路:使用uiautomation进行组件的控制
uiautomation是yinkaisheng开发的基于微软UIAutomation API的一个python模块,支持自动化Win32,MFC,WPF,Modern UI(Metro UI), Qt, IE, Firefox等UI框架

安装

pip install uiautomation

源码

import uiautomation

def getAllControls(control,map):
    if len(control.GetChildren()) != 0:
        for child in control.GetChildren():
            getAllControls(child,map)
    if map.get(control.ControlTypeName) != None:
        map[control.ControlTypeName].append(control)
    else:
        map[control.ControlTypeName] = []
        map[control.ControlTypeName].append(control)


def main():
    control = uiautomation.WindowControl(searchDepth=1,Name="Test")

    controlList = {}
    getAllControls(control,controlList)

    edit = controlList.get("EditControl")[0]
    edit.SendKeys("测试")

    btn = controlList.get("ButtonControl")[3]
    btn.Click()


main()

效果图

2.gif


点墨
26 声望3 粉丝

全栈前端开发工程师