Python控制鍵盤鼠標(biāo)pynput的詳細(xì)用法
pynput這個庫讓你可以控制和監(jiān)控輸入設(shè)備。
對于每一種輸入設(shè)備,它包含一個子包來控制和監(jiān)控該種輸入設(shè)備:
- pynput.mouse:包含控制和監(jiān)控鼠標(biāo)或者觸摸板的類。
- pynput.keyboard:包含控制和監(jiān)控鍵盤的類。
地址: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))
#鼠標(biāo)移動(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)
監(jiān)控鼠標(biāo)事件 :
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')
鍵盤監(jiān)聽:
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()
對于鼠標(biāo)來說,api就上面幾個。但是對于鍵盤來說還要別的,詳細(xì)的查看:http://pythonhosted.org/pynput/index.html
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Python控制鼠標(biāo)鍵盤代碼實例
- python 實現(xiàn)控制鼠標(biāo)鍵盤
- Python 實現(xiàn)鍵盤鼠標(biāo)按鍵模擬
- Python監(jiān)聽鍵盤和鼠標(biāo)事件的示例代碼
- python PyAUtoGUI庫實現(xiàn)自動化控制鼠標(biāo)鍵盤
- Python selenium鍵盤鼠標(biāo)事件實現(xiàn)過程詳解
- Python2.7:使用Pyhook模塊監(jiān)聽鼠標(biāo)鍵盤事件-獲取坐標(biāo)實例
- Python pyautogui模塊實現(xiàn)鼠標(biāo)鍵盤自動化方法詳解
- python模擬鼠標(biāo)點擊和鍵盤輸入的操作
- python使用pynput庫操作、監(jiān)控你的鼠標(biāo)和鍵盤
相關(guān)文章
django寫用戶登錄判定并跳轉(zhuǎn)制定頁面的實例
今天小編就為大家分享一篇django寫用戶登錄判定并跳轉(zhuǎn)制定頁面的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python使用ffmpeg實現(xiàn)將WebM文件轉(zhuǎn)換為MP4文件
這篇文章主要介紹了Python如何使用wxPython庫創(chuàng)建一個簡單的GUI應(yīng)用程序,可以實現(xiàn)將WebM文件轉(zhuǎn)換為MP4文件,文中的示例代碼講解詳細(xì),感興趣的可以動手嘗試一下2023-08-08

