Reputation: 53
I'm trying to run a while loop until the mouse button is released.
I have tried doing something like this using pynput
from pynput.mouse import Listener
mouse = False
# This function will be called when any key of mouse is pressed
def on_click(*args):
# see what argument is passed.
print(args)
if args[-1] and args[-2].name == 'left':
print('The "{}" mouse key has held down'.format(args[-2].name))
mouse = True
while mouse:
# Do stuff
elif not args[-1] and args[-2].name == 'left':
print('The "{}" mouse key is released'.format(args[-2].name))
mouse = False
with Listener(on_click=on_click) as listener:
listener.join()
but it never stops. Is there a way i can just await the mouse up event? Some kind of condition to put in the while loop like
while mouse_down:
# Do stuff until the mouse is released
I've also tried the python mouse libary but it was just acting unexpectedially. Basically i want a while loop to run everytime i press the left mouse until i release it. Is that possible?
Upvotes: 0
Views: 515
Reputation: 13533
Here's a version of your code that continually loops, monitoring the mouse
variable.
from pynput.mouse import Listener
mouse = False
def on_click(*args):
global mouse
if args[-1] and args[-2].name == 'left':
mouse = True
elif not args[-1] and args[-2].name == 'left':
mouse = False
with Listener(on_click=on_click) as listener:
while True:
if mouse:
print("Doing stuff while the mouse is down...")
And here's a version that uses an threading.Event
instead of polling.
from pynput.mouse import Listener
from threading import Event
event = Event()
def on_click(*args):
if args[-1] and args[-2].name == 'left':
event.set()
elif not args[-1] and args[-2].name == 'left':
event.clear()
with Listener(on_click=on_click) as listener:
while event.wait():
print("Doing stuff while the mouse is down....")
Neither of these versions exits gracefully, but I am not familiar enough with pynput.mouse
to fix that.
Upvotes: 1