Use while loop inside pynput's mouse listener

1.4k Views Asked by At

The while loop returns true even when I have let go of the left mouse button which would make pressed = false. I don't know how to break out of the loop to update the pressed value.

from pynput import keyboard
from pynput import mouse
from pynput.mouse import Button, Controller

control = Controller()

def on_click(x, y, button, pressed):
    if button == mouse.Button.left:
        while pressed == True:
            print(pressed)

with mouse.Listener(
        on_click=on_click) as listener:
    listener.join()

Is there any way to update the loop so it knows when pressed = false.

1

There are 1 best solutions below

2
furas On

If you really have to run some loop then you have to do it in separted thread because if you run it in on_click then you block listener and it can't run another on_click

on_click should start loop in thread and use global variable to control when it should stop.

from pynput import mouse
from pynput.mouse import Button, Controller
import threading

control = Controller()

running = False

def process():
    print('start')
    count = 0
    while running:
        print(count)
        count += 1
    print('stop')
    
def on_click(x, y, button, pressed):
    global running # to assing value to global variable (instead of local variable)
    
    if button == mouse.Button.left: 
        if pressed:
            if not running:  # to run only one `process`
                running = True
                threading.Thread(target=process).start()
        else:
            running = False

with mouse.Listener(on_click=on_click) as listener:
    listener.join()