简体   繁体   中英

Move mouse cursor to coordinates that are imported from a text file

I am quite new to Python! I have a text file with some x,y coordinates like so:

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

I am using Pynput to move the mouse to a specific position, such as

mouse.position=(300,500)

I want to be able to have the code read coordinates from the text file "XY_test.txt" so it can print the coordinates and also move the cursor to them.

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()

With this code I can successfully print the coordinates, but the cursor does not move to the desired position. Instead the cursor goes to the position (1,1). It seems that there is a problem with the formatting of the "mouse.position=(coords[i])" line. It expects a value of (x,y), but it apparently reads "1126,600" and puts the first digit as an x-value and the second digit as a y-value. I discovered this when I used "mouse.move(coords[i])" in the place of "mouse.position=(coords[i])" as seen below.

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

I am not sure how to properly have the code read lines of the text file and use them properly as coordinates.

Looks like your list of coords will look something like this:

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

So what you're actually passing to mouse.move() is:

mouse.move('1126, 600') instead of mouse.move(1126, 600) .

What you need to do is split each coord by ' , ' , cast each side to int , then pass those as two separate arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM