我正在创建一个脚本,在该脚本中,如果用户按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]))
侃侃无极
相关分类