pythonpython-3.xkeyboard-eventslistenerspynput

Record mouse click while key is pressed and stop recording when same key is released in python


I am creating a script where if user press f7 it will start recording mouse clicks and when he releases the button it should stop and this happens unless user close the program.

I have written a code which starts recording keys on pressing f7 but when released it still record the key also because key is in continuous pressed position, it keeps on starting multiple listeners and data keeps getting redundant.

Also after releasing f7, listener doesn't stop

Here is the code

from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle

x_pos = []
y_pos = []
both_pos = []
file = open("test.txt", "wb")
file.close()

def on_press(key):

    mouse_listener = mouse.Listener(on_click=on_click)
    if (key==keyboard.Key.f7):
        mouse_listener.start()
        print("done")
def on_release(key):    
    if (key==keyboard.Key.f7):
        mouse_listener.stop()
        print("closing file")
        #file.close()
def on_click(x, y, button, pressed):
    if pressed:
        print ("{0} {1}".format(x,y))
        x_pos.append("{0}".format(x,y))
        y_pos.append("{1}".format(x,y))
        #print (x_pos)
        #print (y_pos)      
        both_pos = x_pos, y_pos
        with open("temp.txt", "ab") as file:
            pickle.dump(both_pos, file)
        print(both_pos)
mouse_listener = mouse.Listener(on_click=on_click)
#mouse_listener.start()
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
    try:
        #listener.start()
        listener.join()
    except MyException as e:
        print('Done'.format(e.args[0]))

Solution

  • You don't have a reference to the same mouse_listener in on_release and on_press.
    Take out mouse_listener = mouse.Listener(on_click=on_click) in on_press and define mouse_listener before both on_press and on_release

    mouse_listener = mouse.Listener(on_click=on_click)
    
    def on_press():
        # do on press stuff with mouse_listener
        pass
    
    def on_release():
        # do on release stuff with mouse_listener
        pass 
    

    It also might be worth wrapping the whole thing in a class