将鼠标光标移动到从文本文件导入的坐标



我对Python很陌生!我有一个带有一些 x,y 坐标的文本文件,如下所示:

1126 , 600
850 , 254
190 , 240
549 , 109

我正在使用 Pynput 将鼠标移动到特定位置,例如

mouse.position=(300,500)

我希望能够让代码从文本文件"XY_test.txt"中读取坐标,以便它可以打印坐标并将光标移动到坐标。

try:
file=open("E:\XY_test.txt",'r')
coords=file.readlines()
for i in range (1,2):
print(coords[i])
mouse.position=(coords[i])
finally:
file.close()

使用此代码,我可以成功打印坐标,但光标不会移动到所需位置。相反,光标转到位置 (1,1(。"mouse.position=(coords[i]("行的格式似乎有问题。它期望的值为 (x,y(,但它显然读取"1126,600",并将第一个数字作为 x 值,将第二个数字作为 y 值。当我使用"mouse.move(coords[i]("代替"mouse.position=(coords[i]("时,我发现了这一点,如下所示。

>>> try:
file=open("E:\XY_test.txt",'r')
coords=file.readlines()
for i in range (1,2):
print(coords[i])
mouse.move(coords[i])
finally:
file.close()

1126 , 600
Traceback (most recent call last):
File "<pyshell#181>", line 6, in <module>
mouse.move(coords[i])
TypeError: move() missing 1 required positional argument: 'dy'

我不确定如何正确读取文本文件的代码行并正确使用它们作为坐标。

看起来您的坐标列表如下所示:

coords=['1126 , 600', 850 , 254', '190 , 240', '549 , 109']

所以你实际上传递给mouse.move()的是:

mouse.move('1126, 600')而不是mouse.move(1126, 600).

你需要做的是按' , 'split每个坐标,将每边投射到int,然后将它们作为两个单独的参数传递。

最新更新