[英]Record (get) mouse click position while key is pressed and stop recording when same key is released in python
I am creating a script where if user press f7 it will start recording mouse clicks and when he releases the button it should stop and this happens unless user closes the program. 我正在创建一个脚本,如果用户按f7键,它将开始记录鼠标的点击,当他释放按钮时,它应该停止,除非用户关闭程序,否则这种情况会发生。
The script is printing "None" inspite of pressing f7 and instead of showing click position and "f7", it is showing None. 尽管按f7键,脚本仍显示“无”,而不显示单击位置和“ f7”,而是显示“无”。
In on_press function when we print the value, it is showing "f7" but when clicking the mouse button in on_click function, it is showing "None" 在on_press函数中,当我们打印值时,它显示为“ f7”,但是在on_click函数中单击鼠标按钮时,则显示为“无”。
Here is the code 这是代码
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]))
Found the issue. 找到了问题。 Because in on_press i was not using global pressed_key so it was creating local variable. 因为在on_press中我没有使用全局pressed_key,所以它正在创建局部变量。
Here is the working code. 这是工作代码。
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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.