实现鼠标控制pynput
为什么不用pyautogui
因为,通过代码测试,移动10次鼠标需要花费将近一秒时间,这个时间效率有点不够用
而pynput只用了几乎0秒
使用方法
首先将鼠标封装成一个类,这样mouse就成为了一个可操作的对象
mouse = pynput.mouse.Controller()
api-mouse.position鼠标位置
保存着鼠标当前的位置(mouse是mouse类实例)
from pynput.mouse import Controller lock_mode = False mouse = Controller() while True: x, y = mouse.position print(x, y)
这段代码实时输出你的鼠标位置。注意哈,你的鼠标位置会受到屏幕缩放设置的影响,不是你是3840x2160,你的鼠标右下角位置就一定是3840x2160.
小demo,鼠标侧键按一下,输出一下
切换---非阻塞版本
from pynput.mouse import Controller lock_mode = False def on_click(x, y, button, pressed): global lock_mode #这里声明使用全局变量 if pressed and button == button.x2: #x1,x2是鼠标侧面肩键 lock_mode = not lock_mode #模式切换 print('','on' if lock_mode else 'off') # Collect events until released with mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() # ...or, in a non-blocking fashion: listener = mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) listener.start()
切换---阻塞版本
import pynput lock_mode = False from pynput import mouse with mouse.Events() as events: while True: it = next(events) #当有操作且不是左键单击则读取下一个操作 while it is not None and not isinstance(it, pynput.mouse.Events.Click): it = next(events) if it is not None and it.button == it.button.x2 and it.pressed: lock_mode = not lock_mode print('','on' if lock_mode else 'off')