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.
- pyautogui (for a mouse click or button press)
- 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.