使用Python 的GUI 自动化
在本文中,我们将探讨如何使用Python进行 GUI 自动化。有很多模块可以做这些事情,但在本文中,我们将使用一个名为PyAutoGUI的模块来使用Python执行 GUI 和桌面自动化。
我们将探索两个部分——
- 如何自动使用鼠标指针执行某些任务,例如移动光标、单击屏幕上的某个点等
- 此外,我们将探索如何使键盘击键自动化。
安装
这个模块没有预装Python。要安装它,请在终端中键入以下命令。
pip install pyautogui # for windows
or
pip3 install pyautogui #for linux and Macos
入门
在进行任何自动化之前,我们应该知道我设备的屏幕尺寸。幸运的是,PyautoGUI 可以帮助我们使用 .size()函数轻松获取它。它返回一个带有两个值的大小对象,分别代表屏幕的宽度和高度。实现如下。
Syntax: pyautogui.size()
Parameters: This function does not take any extra parameters
Return Type: It returns us the size of the present screen in pixels in a Size object
下面是实现:
Python3
# importing modules
import pyautogui
# returns a size object with
# width and height of the screen
print(pyautogui.size())
Python3
import pyautogui
# returns a point object with
# x and y values
print(pyautogui.position())
Python3
import pyautogui
# moves to (519,1060) in 1 sec
pyautogui.moveTo(519, 1060, duration = 1)
# simulates a click at the present
# mouse position
pyautogui.click()
# moves to (1717,352) in 1 sec
pyautogui.moveTo(1717, 352, duration = 1)
# simulates a click at the present
# mouse position
pyautogui.click()
Python3
import pyautogui
# moving the cursor left 498 px & down
# 998px from it's current position
pyautogui.moveRel(-498,996, duration = 1)
# clicks at the present location
pyautogui.click()
# moves to the specified location
pyautogui.moveTo(1165,637, duration = 1)
# right clicks at the present cursor
# location
pyautogui.click(button="right")
# moves to the specified location
pyautogui.moveTo(1207,621, duration = 1)
# clicks at the present location
pyautogui.click()
Python3
import pyautogui
# cursor moves to a specific position
pyautogui.moveTo(519,1060, duration = 1)
# left clicks at the current position
pyautogui.click()
# cursor moves to a specific position
pyautogui.moveTo(1550,352, duration = 1)
# left clicks and holds and moves the
# curson to (500,500) position
pyautogui.dragTo(500,500, duration = 1)
# drags the cursor relative to it's
# position to 5opx right and 50 px down
pyautogui.dragRel(50,50, duration=1)
Python3
# used to access time related functions
import time
import pyautogui
# pauses the execution of the program
# for 5 sec
time.sleep(5)
# types the string passed inside the
# function
pyautogui.typewrite("Geeks For Geeks!")
Python3
# used to access time related functions
import time
import pyautogui
# pauses the execution of the program
# for 5 sec
time.sleep(5)
# types the string passed inside the
# function
pyautogui.typewrite("Geeks For Geeks!")
# simulates pressing the enter key
pyautogui.press("enter")
# simulates pressing the hotkey ctrl+a
pyautogui.hotkey("ctrl","a")
Python3
import pyautogui
# a alert displays with a ok button
# on it
pyautogui.alert(text='', title='', button='OK')
# a confirm dialog box appears with ok
# and cancel buttons on it
pyautogui.confirm(text='', title='', buttons=['OK', 'Cancel'])
# a prompt displays that lets you to
# write something
pyautogui.prompt(text='', title='' , default='')
# a password field appears with entry box
# to fill a password
pyautogui.password(text='', title='', default='', mask='*')
Python3
import pyautogui
# takes a screenshot of the present
# window and stores it as "123.png"
pyautogui.screenshot("123.png")
输出:
Size(width=1920, height=1080)
自动化鼠标移动
获取鼠标光标的当前位置:
首先,我们将当前鼠标光标所在的位置,为此我们可以使用 .position()函数。该函数再次返回一个带有 x 和 y 值的点对象,用于获取鼠标的当前位置。
Syntax: pyautogui.position()
Parameters: This function does not take any extra parameters
Return Type: It returns us the position of the mouse cursor in a Point object
下面是实现:
蟒蛇3
import pyautogui
# returns a point object with
# x and y values
print(pyautogui.position())
输出:
Point(x=1710, y=81)
移动光标并单击特定点:
现在我们将尝试移动鼠标光标并单击特定位置并执行打开应用程序和关闭它。为了移动鼠标指针,我们可以使用 .moveto() 并指定 x,y 值以及它将执行操作的持续时间,我们将使用 .click()函数单击鼠标指针所在的位置位于现在。代码基本上将鼠标光标移动到 (519,1060) (x,y) 值,然后使用光标现在所在的 .click() 模拟单击,然后我们再次移动到位置 (1717,352)使用 moveTo() 并再次模拟单击。
Syntax: pyautogui.moveTo() and pyautogui.click()
Parameters: This moveTo function has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. The click method in the example doesn’t take any parameter but an optional pair of parameters can be used to click a particular position on the keyboard.
Return Type: The functions don’t return anything but performs the jobs of the cursor to a specific point and then clicking there programmatically.
下面是实现:
蟒蛇3
import pyautogui
# moves to (519,1060) in 1 sec
pyautogui.moveTo(519, 1060, duration = 1)
# simulates a click at the present
# mouse position
pyautogui.click()
# moves to (1717,352) in 1 sec
pyautogui.moveTo(1717, 352, duration = 1)
# simulates a click at the present
# mouse position
pyautogui.click()
输出:
现在我们将探索另外两种方法,即 .moveRel() ,它帮助我们相对于我们现在所处的位置移动,最后我们将看到如何使用 pyAutoGUI 模拟右键单击。我们从导入包开始,并刺激光标从当前位置移动 498 像素并向下移动 998 像素。然后我们使用 click() 方法来模拟左键单击。然后我们使用 .moveTo() 方法移动到特定位置。现在我们再次单击光标的当前位置,但这次我们通过传递 button="right" 参数(默认为 button="left")来指示模拟右击而不是左击。然后我们获得移动到指定位置并在那里左键单击。
Syntax: pyautogui.moveRel()
Parameters: This moveRel function has also two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. Also, we used an extra parameter for the pyautogui.click() function, we used button=”right” which simulates a right-click instead of the default left-click.
Return Type: The functions don’t return anything but perform the jobs of moving the cursor left 498 px & down 998px from it’s current position and then simulate a right-click programmatically.
下面是实现:
蟒蛇3
import pyautogui
# moving the cursor left 498 px & down
# 998px from it's current position
pyautogui.moveRel(-498,996, duration = 1)
# clicks at the present location
pyautogui.click()
# moves to the specified location
pyautogui.moveTo(1165,637, duration = 1)
# right clicks at the present cursor
# location
pyautogui.click(button="right")
# moves to the specified location
pyautogui.moveTo(1207,621, duration = 1)
# clicks at the present location
pyautogui.click()
输出:
将光标拖动到特定的屏幕位置:
现在我们将看到如何使用 pyAutoGUI 拖动窗口。我们可以使用 .dragto() 和 .dragrel() ,它们与 .moveto() 和 .movrel() 的工作方式完全相同,除了在这种情况下,它们在移动光标时按住左键单击。在这个程序中,我们简单地导入模块,然后使用 .moveTo()函数移动到指定的位置。然后我们在光标的当前位置左键单击。现在我们再次将光标移动到指定位置。然后我们使用 .dragTo()函数将 拖动(左键单击并按住)到特定位置。最后,我们使用 dragRel()函数将光标相对于其当前位置向右拖动 50 像素,向下拖动 50 像素。
Syntax: pyautogui.dragTo() and pyautogui.dragRel()
Parameters: Both the functions has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter.
Return Type: The functions don’t return anything but perform the jobs of left-click and holding and moves the cursor to (500,500) position and drags the cursor relative to it’s position to 5opx right and 50 px down programmatically.
下面是实现:
蟒蛇3
import pyautogui
# cursor moves to a specific position
pyautogui.moveTo(519,1060, duration = 1)
# left clicks at the current position
pyautogui.click()
# cursor moves to a specific position
pyautogui.moveTo(1550,352, duration = 1)
# left clicks and holds and moves the
# curson to (500,500) position
pyautogui.dragTo(500,500, duration = 1)
# drags the cursor relative to it's
# position to 5opx right and 50 px down
pyautogui.dragRel(50,50, duration=1)
输出:
注意: .moveTo()、.moveRel()、.dragTo() 和.dragRel() 函数中的Duration 参数是可选的,但提供它是为了获得动画效果,没有属性函数将立即执行,它将很难理解。我们还可以选择在 .click()函数传递 x 和 y 值,该函数可用于单击光标当前所在位置的不同位置。
自动化键盘
用键盘自动打字:
首先,我们将学习如何使用 pyAutoGUI 模拟输入内容。在此示例中,我们将使用 .typewrite()函数在记事本文件中键入一些内容。在这段代码中,我们首先导入 time 和 pyAutoGUI 模块,然后使用 time.sleep()函数将程序的执行暂停指定的几秒钟。然后我们使用 pyautogui.typewrite()函数来模拟字母数字键的输入。将键入引号内的短语。实现如下:
Syntax: pyautogui.typewrite()
Parameters: The function has only one parameter which is the string that needs to be typed.
Return Type: The functions don’t return anything but perform the jobs of simulating the typing of a string that is passed inside it.
下面是实现:
蟒蛇3
# used to access time related functions
import time
import pyautogui
# pauses the execution of the program
# for 5 sec
time.sleep(5)
# types the string passed inside the
# function
pyautogui.typewrite("Geeks For Geeks!")
输出:
按特定键并模拟热键:
接下来,我们将探索两个函数,第一个是 .press(),第二个是 .hotkey(),第一个帮助您按下通常用于按下非字母数字键的键,而 .hotkeys() 函数帮助您我们按下 ctrl+shift+esc 等热键。这里我们也通过导入两个模块 time 和 pyAutoGUI 来启动代码。然后我们使用 sleep函数暂停程序的执行 5 秒钟。我们使用 typewrite函数输入字符串。然后我们使用 .press()函数来模拟按键,最后使用 .hotkey()函数来模拟热键的按下。在我们的示例中,我们使用热键 ctrl+a 来选择所有文本。实现如下:
Syntax: pyautogui.press() and pyautogui.hotkey()
Parameters: The .press() function has only one parameter which is the key that needs to be pressed and the .hotkey() function has a number of parameters depending upon the number of keys to simulate the hotkey action.
Return Type: The functions don’t return anything but perform the job of simulating of pressing the enter key and simulates pressing the hotkey ctrl+a.
下面是实现:
蟒蛇3
# used to access time related functions
import time
import pyautogui
# pauses the execution of the program
# for 5 sec
time.sleep(5)
# types the string passed inside the
# function
pyautogui.typewrite("Geeks For Geeks!")
# simulates pressing the enter key
pyautogui.press("enter")
# simulates pressing the hotkey ctrl+a
pyautogui.hotkey("ctrl","a")
输出:
显示消息框
现在我们将尝试探索 pyAutoGUI 提供给我们的一些跨平台 JavaScript 样式的消息框。它使用 Tkinter 和 PyMsgBox 模块来显示这些框。代码从导入模块开始,然后我们使用不同的消息框来显示不同的消息。 .alert()函数显示一个警报,我们在其中使用“确定”按钮将标题和文本设置为空白。然后 .confirm()函数显示一个确认对话框,我们再次将标题和文本设置为空白,并保留两个按钮“确定”和“取消”按钮。然后 .prompt()函数显示一个确认提示框,我们在其中再次将标题、文本和默认值(用户开始输入之前提示框中默认写入的内容)设置为空白。最后,.password()函数显示一个密码对话框,我们再次将标题和文本设置为空白,并将掩码(被替换的字符而不是密码中的原始字母)设置为“*”。实现如下:
Syntax: pyautogui.alert(), pyautogui.confirm(), pyautogui.prompt() and pyautogui.password()
Parameters: The .alert() function has three parameters defining the title, text and buttons to be placed. The .confirm() function also has three parameters for text, title and buttons. The .prompt() function has three parameters for text, title and default value. The .password() has four parameters for text, title, default value and mask (The character that gets replaced instead of the original letters in the password).
Return Type: The functions don’t return anything but show up an alert in which we set the title and text to be blank with an “OK” button. Then it displays a confirm dialogue box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialogue box in which we again set the title and text to be blank and set the mask to be “*”.
下面是实现:
蟒蛇3
import pyautogui
# a alert displays with a ok button
# on it
pyautogui.alert(text='', title='', button='OK')
# a confirm dialog box appears with ok
# and cancel buttons on it
pyautogui.confirm(text='', title='', buttons=['OK', 'Cancel'])
# a prompt displays that lets you to
# write something
pyautogui.prompt(text='', title='' , default='')
# a password field appears with entry box
# to fill a password
pyautogui.password(text='', title='', default='', mask='*')
输出:
截屏
最后,我们将看到如何使用 .screenshot()函数使用 pyAutoGUI 截取屏幕截图。我们将从导入 pyAutoGUI 模块开始。然后我们使用 .screenshot()函数将当前窗口的屏幕截图保存为“123.png”在同一个目录中,为了保存在另一个目录中,我们需要提供它的相对或绝对路径。实现如下:
Syntax: pyautogui.screenshot()
Parameters: The function has one optional parameter which is the path of the file along with the filename in which the screenshot needs to be stored.
Return Type: The function doesn’t return anything but takes a screenshot and stores it in the path passed inside it as a parameter.
下面是实现:
蟒蛇3
import pyautogui
# takes a screenshot of the present
# window and stores it as "123.png"
pyautogui.screenshot("123.png")
输出: