This is my code, and in the line, I put a commentary about the return
that makes this problem.
from pynput import mouse
def on_move(m_x, m_y):
print('Pointer moved to {0}'.format((m_x, m_y)))
def on_click(m_x, m_y, button, pressed):
#print('{0} at {1}'.format('Pressed' if pressed else 'Released',(m_x, m_y)))
if(pressed):
print("Pressed")
else:
print("( x = " str(m_x) ", y = " str(m_y) " )")
return(m_x, m_y) #this is the return
if not pressed:
# Stop listener
return False
def on_scroll(m_x, m_y, dm_x, dm_y):
print('Scrolled {0} at {1}'.format(
'down' if dy < 0 else 'up',
(m_x, m_y)))
# Collect events until released
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
A_coord_x, A_coord_y = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
#listener.start()
print (A_coord_x)
print (A_coord_y)
The only thing I want is that after giving a click the coordinates are saved in the variables A_coord_x
and A_coord_y
CodePudding user response:
on_click()
is an event handler, you can't return values from it, the return False statement just stops the listener. Just call a set_coordinates(x,y) function from within the handler and you should get your intended result.
Maybe also take a look at the documentation, there is an example on how to work with the mouse.listener
CodePudding user response:
here is the answer for you. this will release the listener
and get you the coordinates in A_coord_x
and A_coord_y
from pynput.mouse import Listener
A_coord_x, A_coord_y = 0, 0
def on_click(x, y, button, pressed):
global A_coord_x, A_coord_y
if pressed:
A_coord_x, A_coord_y = x, y
print('{0} at {1}'.format(
'Pressed' if pressed else 'Released',
(x, y)))
return x,y
if not pressed:
# Stop listener
return False
with Listener(on_click=on_click) as listener:
coords = listener.join()
print ('X coordinates :',A_coord_x)
print ('Y coordinates :',A_coord_y)
output:
Pressed at (1211, 400)
X coordinates : 1211
Y coordinates : 400