我正在创建一个脚本,如果用户按下 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]))