Search code examples
pythonautomationpyautogui

Moving the cursor in relation to a certain fix-point in Python


is there any possibility to move the cursor in Python with % starting from a certain coordinate like (1,1)? I am using pyautogui atm to automate and I thought it would be quite convenient if this is independent from the monitor size making it universal.

Thanks for your help in advance!


Solution

  • It's possible indirectly. As detailed at the top of the Mouse Control Functions page of the documentation, you can get the screen size using the size() function (which returns a tuple of (X, Y)). You can then do the math to figure out how many screen pixels equal the percentage you're looking for, then call moveTo() to go there.

    # script to move mouse 50% to the right and down
    import pyautogui as pag
    
    percentage = 0.5
    cur_X, cur_Y = pag.position() # current X and Y coordinates
    size_X, size_Y = pag.size() # screen size
    goto_X = (size_X - cur_X) * percentage + cur_X # current location plus half
    goto_Y = (size_Y - cur_Y) * percentage + cur_Y # the distance to the edge
    
    pag.moveTo(goto_X, goto_Y, 1) # move to new position, taking 1 second