控制鼠标
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) # 放开鼠标左键 # 点击鼠标 mouse.click(Button.left, 2) # 点击鼠标2下 # 鼠标滚轮 mouse.scroll(0, 2) # 滚动鼠标
监听鼠标
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 print(button) # 左右键(Button.left、Button.right、Button.middle) print(pressed) # 左键(left)、右键(right)、滚轮(Button.middle)的按压状态(True,False)
def on_scroll(x, y, dx, dy):
# 监听鼠标滚轮
print('Scrolled {0}'.format((x, y))) # 坐标
print(dx, dy) # dy(-1:下滚,1:上滚)dx(0)
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
控制键盘
from pynput.keyboard import Key,Controller,Listener keyboard = Controller() keyboard.press("a") #按下a keyboard.release("a") #松开a keyboard.press("A") #按下A keyboard.release("A") #松开A with keyboard.pressed(Key.shift): #按下shift keyboard.press("a") #shift + a keyboard.type("Hello World") #输出文字
监听键盘
from pynput.keyboard import Listener def press(key): print(key) if key == 'Q': return False with Listener(on_press=press) as listener: listener.join() listener.stop()