Python库PyAutoGUI应用实例



简 介:本文收集了一些PyAutoGUI的一些应用实例项目。

关键词 PyAutoGUIPython应用举例

§01 制方形螺旋形状


  下面是一个在 MS Paint(或任何图形绘制程序)中以方形螺旋形状拖动鼠标的例子。

import pyautogui
distance = 200
while distance > 0:
	pyautogui.drag(distance, 0, duration=0.5)   # move right
	distance -= 10
	pyautogui.drag(0, distance, duration=0.5)   # move down
	pyautogui.drag(-distance, 0, duration=0.5)  # move left
	distance -= 10
	pyautogui.drag(0, -distance, duration=0.5)  # move up


▲ 图1 使用PyAutoGUI在MS Paint中绘制的方形螺旋形状

  与直接生成图像文件的脚本相比,使用 PyAutoGUI 的好处是您可以使用 MS Paint 提供的画笔工具。

§02 取鼠标的实时位置


import pyautogui, time
print('按下 Ctrl-C 可退出!')
try:
    while True:
        x, y = pyautogui.position()
        positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
        print(positionStr)
        time.sleep(0.5)
except KeyboardInterrupt:
    print('\n')
▲ 图2 获取鼠标的实时位置源代码与运行结果显示

注:代码中 rjust()返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串。如果指定的长度小于字符串的长度则返回原字符串。详见 Python rjust()方法

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 当然可以!下面是一个使用 PyAutoGUI 模拟打开记事本并输入文本的简单示例: ``` import pyautogui # 打开记事本 pyautogui.hotkey('winleft', 'r') pyautogui.typewrite('notepad\n') # 在记事本中输入文本 pyautogui.typewrite("Hello, I'm using PyAutoGUI!") ``` 这段代码会打开「运行」窗口,然后输入「notepad」并回车,最后在记事本中输入「Hello, I'm using PyAutoGUI!」。 ### 回答2: 当然可以!下面是一个使用pyautogui模块的简单示例: ```python import pyautogui import time # 移动鼠标到屏幕中心并点击 screen_width, screen_height = pyautogui.size() center_x = screen_width // 2 center_y = screen_height // 2 pyautogui.moveTo(center_x, center_y) # 移动鼠标到屏幕中心 pyautogui.click() # 点击鼠标左键 time.sleep(2) # 等待2秒 # 在画图程序中绘制一个矩形 pyautogui.moveTo(100, 100) # 移动鼠标到坐标(100, 100) pyautogui.dragRel(200, 150, duration=1) # 从当前位置向相对坐标拖拽鼠标到(300, 250) time.sleep(2) # 等待2秒 # 打开文本编辑器并输入一段文字 pyautogui.hotkey('command', 'space') # 打开Spotlight搜索 pyautogui.typewrite('textedit') # 输入文本编辑器的名称 pyautogui.press('enter') # 按下Enter键以打开文本编辑器 time.sleep(2) # 等待2秒 pyautogui.typewrite('Hello, pyautogui!') # 在文本编辑器中输入文字 ``` 以上代码演示了pyautogui模块的几个基本用法,包括移动鼠标、点击鼠标、拖拽鼠标以及模拟键盘按键操作。在实际应用中,pyautogui可以用于自动化测试、图形界面自动化操作等场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43964993

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值