我正在创建一个脚本,如果用户按下f7键,它将开始记录鼠标的点击,而当他释放按钮时,它应该停止,除非用户关闭程序,否则这种情况会发生。
尽管按f7键,脚本仍打印“无”,而不显示单击位置和“ f7”,而是显示“无”。
在on_press函数中,当我们打印值时,它显示为“ f7”,但是在on_click函数中单击鼠标按钮时,则显示为“无”。
这是代码
from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle
x_pos = []
y_pos = []
both_pos = []
pressed_key = None
def on_press(key):
if (key==keyboard.Key.f7):
pressed_key = "f7"
else:
pressed_key = None
def on_release(key):
pass
def on_click(x, y, button, pressed):
if pressed:
#print ("{0} {1}".format(x,y))
print(pressed_key)
if pressed_key == "f7":
x_pos.append("{0}".format(x,y))
y_pos.append("{1}".format(x,y))
#print("test" + x_pos + y_pos)
print (x_pos + y_pos)
#both_pos = x_pos, y_pos
else:
pass
print (x_pos + y_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]))
答案 0 :(得分:0)
发现了问题。因为在on_press中我没有使用全局pressed_key,所以它正在创建局部变量。
这是工作代码。
from pynput import mouse, keyboard
from pynput.keyboard import Key, Listener
import pickle
x_pos = []
y_pos = []
both_pos = []
pressed_key = None
def on_press(key):
global pressed_key
if (key==keyboard.Key.f7):
pressed_key = "f7"
print(pressed_key)
else:
pressed_key = None
def on_release(key):
global pressed_key
pressed_key = None
def on_click(x, y, button, pressed):
if pressed:
#print ("{0} {1}".format(x,y))
print(pressed_key)
if pressed_key == "f7":
x_pos.append("{0}".format(x,y))
y_pos.append("{1}".format(x,y))
#print("test" + x_pos + y_pos)
print (x_pos + y_pos)
#both_pos = x_pos, y_pos
else:
pass
print (x_pos + y_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]))