在按下键时记录鼠标单击,并在python中释放相同键时停止记录

时间:2018-08-03 10:50:27

标签: python python-3.x keyboard-events listeners pynput

我正在创建一个脚本,如果用户按下f7键,它将开始记录鼠标的点击,而当他释放按钮时,它将停止,除非用户关闭程序,否则这种情况会发生。

我编写了一个代码,该代码在按f7键时开始记录键,但是释放时它仍会​​记录键,因为键一直处于连续按下位置,因此它会继续启动多个侦听器,并且数据会变得越来越多余。

释放f7之后,监听器也不会停止

这是代码

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]))

1 个答案:

答案 0 :(得分:1)

mouse_listeneron_release中没有引用相同的on_press
mouse_listener = mouse.Listener(on_click=on_click)中取出on_press,并在mouse_listeneron_press之前定义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 

将整个内容包装在一个类中也许也是值得的