如何在pyautogui中实现平滑的鼠标移动而不是回合点之间的传送? 如何设置鼠标移动的路径,而不仅仅是传送,除非您尝试手动插入几个小时?
Pyautogui 是一个用于自动化的库,并不用于平滑移动,请考虑其他库。
为了实现适当的平滑运动,尤其是曲线运动,我们使用数学函数来确定路径和循环来增加 x 坐标(在我的示例中,x 坐标是“a”,y 坐标是“b”)。
在编写代码之前,使用Desmos一张纸或不同的图形计算器来可视化函数的图形。
重要提示: y 坐标在 pyautogui 中是倒置的,请考虑这一点。
我使用“x”和“y”变量作为屏幕在各自轴上的中心,但您可以通过替换它们从任何地方开始。
然后我们将
pyautogui.pause
设置为 0,这样运动之间就没有暂停。在此之后,请注意它已损坏,持续时间值高于 0.2 会产生缓慢的速度,并且 <= 0.2 offer very high speed, this is clearly not meant to be used for this but it works. By setting the duration to 0.2 we can edit our step (the incrementation of the function) to achieve the necessary speed. And it is smooth.
这是一个功能示例:它用鼠标绘制一个无穷大符号。确保您能够在 IDE 中停止它,在 Pycharm 中是 ctrl+F2。
import pyautogui
import time
screenSize = pyautogui.size()
x = screenSize[0]/2
y = screenSize[1]/2
time.sleep(3)
# SETTINGS
pyautogui.PAUSE = 0
# Multiplier
size = 100
# Duration
speed = 0.2
# Incrementation
step = 0.0001
pyautogui.moveTo(x, y, 0)
a = step
loopStart = True
while True:
if loopStart:
while True:
a += step
b = -(a - 2) * 0.5 - 1
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a >= 2:
break
while True:
a += step
b = (((a - 2) ** 4) * 0.8) - 1
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a >= 3:
a += step
break
while True:
a -= step
b = -(((a - 2) ** 4) * 0.8) + 1
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a <= 2:
a -= step * 2
break
while True:
a -= step
b = a * 0.5
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a <= -2:
a += step
break
# Side 2
while True:
a -= step
b = (((a + 2) ** 4) * 0.8) - 1
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a <= -3:
a -= step
break
while True:
a += step
b = -(((a + 2) ** 4) * 0.8) + 1
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a >= -2:
a += step*2
break
while True:
a += step
b = -(a + 2) * 0.5 + 1
pyautogui.moveTo(x + a * size, y + b * size, speed * 0.5, pyautogui.linear)
if a >= 2:
loopStart = False
break
# I think this is also accomplishable by running stuff in parallel but this weird method is better anyway.
# Ideally you want to use a proper library like now broken Autopy for this.
我知道这是一个高度要求的问题,但还没有找到一个正确的答案,这让我很奇怪,并导致创建了这篇 QnA 风格的帖子。希望有人觉得这很有用<3
您可以使用持续时间
pyautogui.moveTo(x, y, duration=0.3)