当前位置:   article > 正文

python 控制和监控鼠标输入 pynput模块_mouse.listener python

mouse.listener python

控制鼠标输入

使用 pynput.mouse.Controller 来实现

from pynput.mouse import Button, Controller

mouse = Controller()

# 读取鼠标的位置
print('The current pointer position is {0}'.format(
    mouse.position))

# 设置鼠标的位置
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# 以当前鼠标位置为原点来移动鼠标
mouse.move(5, -5)

# 按下鼠标和释放鼠标
mouse.press(Button.left)
mouse.release(Button.left)

# 双击
# twice on macOS
mouse.click(Button.left, 2)

# 滚动鼠标
mouse.scroll(0, 2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

监测鼠标

用 pynput.mouse.Listener 来实现

from pynput import mouse

# 监测鼠标移动,坐标值
def on_move(x, y):
    print('Pointer moved to {0}'.format(
        (x, y)))

# 监测鼠标点击
def on_click(x, y, button, pressed):
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

# 监测鼠标滚动
def on_scroll(x, y, dx, dy):
    print('Scrolled {0} at {1}'.format(
        'down' if dy < 0 else 'up',
        (x, y)))

# 鼠标的监听器是 threading.Thread,并且所有的回调函数都会在线程中被调用
#  可以手动调用 pynput.mouse.Listener.stop 来触发StopException或从回调函数中返回False,实现线程终止
with mouse.Listener(
        on_move=on_move,
        on_click=on_click,
        on_scroll=on_scroll) as listener:
    listener.join()

# 以非阻塞的方式运行
listener = mouse.Listener(
    on_move=on_move,
    on_click=on_click,
    on_scroll=on_scroll)
listener.start()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

鼠标监测线程可以直接从其他线程调用,这意味着如果没有设置回调函数,将会阻塞所有进程的输入,一个可能的解决办法是将其传入消息队列,然后用一个单独的线程来进行管理
如果回调处理程序引发异常,则监测器将停止。由于回调在专用的线程中运行,因此不会自动引发异常。要获得有关回调错误的通知,需要在实例上调用 Thread.join

from pynput import mouse

class MyException(Exception): pass

def on_click(x, y, button, pressed):
    if button == mouse.Button.left:
        raise MyException(button)

# Collect events until released
with mouse.Listener(
        on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        print('{0} was clicked'.format(e.args[0]))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/839567
推荐阅读
相关标签
  

闽ICP备14008679号