pythonkeyboardpyautogui

get position of mouse in python on click or button press


I want to get the x, y position of the mouse (in windows 11) and use this position in the rest of the code.

I have tried two different modules but neither seem to work.

  1. pyautogui (for a mouse click or button press)
  2. keyboard (for a button press)

So far, i am able to get the current position (with pyautogui), but i cannot break out of the while loop to proceed to the next piece of code or even return the function.

Here is the function with my attempts:

import time
import pyautogui
import keyboard

def spam_ordinates():
    ''' function to determin the mouse coordinates'''

    print('press "x" key to lock position...')

    while True:
        # Check if the left mouse button is clicked
        time.sleep(0.1)
        print(pyautogui.displayMousePosition())

        # various methods i have tried ...
        if keyboard.is_pressed('x'):
            print('x key pressed...')
            break

        if pyautogui.mouseDown():
            print("Mouse clicked!")
            break

        if pyautogui.keyDown('x'):
            print('x key pressed (autogui)...')
            break

    # Get the current mouse position
    x, y = pyautogui.position()
    print(f'spam at position: {x}, {y}')

    return x, y

# call function
ords = spam_ordinates()

i see answers like this: Python get mouse x, y position on click, but unfortunately it doesn't actually return a value on the mouse click or button press.

So, how can i break out of the while loop such that the function returns the x, y position of the mouse?

update

it appears as though print(pyautogui.displayMousePosition()) was preventing the code from breaking out of the while loop.

I am not sure why, but commenting out that line corrected the issue.


Solution

  • I noticed that for some reason the print(pyautogui.displayMousePosition()) line of code was creating problems from breaking out of the loop.

    when the above print statement was removed, i was able to use any of the modules:

    so this code works with the `keyboard module:

    def spam_ordinates():
        ''' function to determin the mouse coordinates'''
    
        print('press "x" key to lock position...')
    
        while True:
            # Check if x key is pressed
            time.sleep(0.1)
    
            if keyboard.is_pressed('x'):
                print('x key pressed...')
                break
    
        # Get the current mouse position
        x, y = pyautogui.position()
        print(f'spam at position: {x}, {y}')
    
        return x, y
    

    I cannot explain completely why print(pyautogui.displayMousePosition()) caused this error, other than it must have been blocking the if statements that would have evoked the break.

    I post this answer in case anybody else encounters the same.