我正在创建一个脚本,在该脚本中,如果用户按f7键,它将开始记录鼠标的点击,而当他释放按钮时,它应该停止,除非用户关闭程序,否则这种情况会发生。我编写了一个代码,该代码在按f7键时开始记录键,但是放开它仍会记录该键,这也是因为键处于连续按下位置,它会继续启动多个侦听器,并且数据会变得越来越多余。同样在释放f7之后,监听器不会停止这是代码from pynput import mouse, keyboardfrom pynput.keyboard import Key, Listenerimport picklex_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 回答
侃侃无极
TA贡献2051条经验 获得超10个赞
您mouse_listener在on_release和中没有相同的引用on_press。
取出mouse_listener = mouse.Listener(on_click=on_click)在on_press和界定mouse_listener既之前on_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
将整个内容包装在一个类中可能也值得
添加回答
举报
0/150
提交
取消