【问题标题】:Move mouse cursor to coordinates that are imported from a text file将鼠标光标移动到从文本文件导入的坐标
【发布时间】:2020-05-14 06:35:31
【问题描述】:

我对 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'

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

【问题讨论】:

  • 当你从文件中读取时,它是一个字符串还是一个数字?
  • How to debug small programs。在循环中,打印coords[i] - 会发生什么?为什么?
  • ...don't know what to try next - 欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。花点时间和the Tutorial一起练习例子。

标签: python coordinates cursor-position pynput


【解决方案1】:

您的坐标列表看起来像这样:

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

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

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

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

【讨论】:

  • @GinoCheeseSteaks 很高兴它成功了!如果问题已解决,请在我的答案上打勾以将其标记为正确。干杯:)
猜你喜欢
  • 2012-05-11
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 1970-01-01
  • 2021-08-12
相关资源
最近更新 更多