Python pynput库实现键盘鼠标控制的详细指南

江屿
江屿
发布时间:2026-10-13 | 6人浏览过
原创

本文详细介绍Python库pynput的使用方法,涵盖鼠标位置获取、移动、点击及滚动操作,以及键盘按键监听与模拟。通过具体代码示例展示如何监控鼠标事件和捕获键盘输入,帮助开发者实现自动化脚本和输入设备控制功能。

pynput库提供了对输入设备的控制与监控功能。

针对不同类型的输入设备,该库提供了相应的子模块进行专门处理:

  • pynput.mouse模块提供了用于控制和监控鼠标或触控板的类。
  • pynput.keyboard模块提供了用于控制和监控键盘的类。

官方仓库地址:https://pypi.python.org/pypi/pynput

以下是基本使用方法的介绍:

from pynput.mouse import Button, Controller
import time 

mouse = Controller()
print(mouse.position)
time.sleep(3)
print('The current pointer position is {0}'.format(mouse.position))


#set pointer positon
mouse.position = (277, 645)
print('now we have moved it to {0}'.format(mouse.position))

#鼠标移动(x,y)个距离
mouse.move(5, -5)
print(mouse.position)

mouse.press(Button.left)
mouse.release(Button.left)

#Double click
mouse.click(Button.left, 1)

#scroll two steps down
mouse.scroll(0, 500)

监控鼠标事件的具体实现如下:

from pynput import mouse

def on_move(x, y ):
 print('Pointer moved to {o}'.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:
  return False

def on_scroll(x, y ,dx, dy):
 print('scrolled {0} at {1}'.format(
  'down' if dy < 0 else 'up',
  (x, y)))

while True:
 with mouse.Listener( no_move = on_move,on_click = on_click,on_scroll = on_scroll) as listener:
  listener.join()

键盘输入的控制方法如下:

from pynput.keyboard import Key, Controller

keyboard = Controller()
# 按下空格和释放空格
#Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
# 按下a键和释放a键
#Type a lower case A ;this will work even if no key on the physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')

#Type two upper case As
keyboard.press('A')
keyboard.release('A')
# or 
with keyboard .pressed(Key.shift):
 keyboard.press('a')
 keyboard.release('a')

#type 'hello world ' using the shortcut type method
keyboard.type('hello world')

键盘监听功能的实现代码如下:

from pynput import keyboard

def on_press(key):
 try:
  print('alphanumeric key {0} pressed'.format(key.char))
 except AttributeError:
  print('special key {0} pressed'.format(key))

def on_release(key):
 print('{0} released'.format(key))
 if key == keyboard.Key.esc:
  return False

while True:
 with keyboard.Listener(
  on_press = on_press,
  on_release = on_release) as listener:
  listener.join()

鼠标相关的API主要包含上述几种。对于键盘功能,如需了解更多详细信息,请参考官方文档:http://pythonhosted.org/pynput/index.html

以上就是本文的全部内容,希望对各位的学习有所帮助,也欢迎大家继续支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表