python --监听鼠标事件
from pynput.mouse import Listener, Button
# 定义一个全局变量用于记录左键是否被按下
left_click_pressed = False
# 定义一个全局变量用于记录左键按下时的位置
click_x, click_y = None, None
# 监听鼠标按下事件
def on_click(x, y, button, pressed):
global left_click_pressed, click_x, click_y
print(x)
print(y)
print(button)
print(pressed)
if button == Button.left: # 1代表鼠标左键
if pressed:
left_click_pressed = True
click_x, click_y = x, y
# 左键被按下时停止监听器
listener.stop()
# 启动监听器
with Listener(on_click=on_click) as listener:
listener.join()
# 输出左键被按下时的位置
print(f"左键被按下时的位置: x={click_x}, y={click_y}")