python控制鼠标键盘:pynput

环境:win10,python3.5

安装pynput

pip install pynput

鼠标的控制与监听

import pynput

mouse = pynput.mouse.Controller()

# 移动鼠标到绝对坐标与相对坐标
mouse.position = (0, 0)
mouse.move(dx=5, dy=-5)

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

# 点击鼠标次数
mouse.click(pynput.mouse.Button.left, count=2)	

# 滚轮
mouse.scroll(dx=0, dy=2)			

def on_move(x, y):
    print("pointer moved to {}".format((x, y)))

def on_click(x, y, button, pressed):
    print("{} at {}".format("pressed" if pressed else "released", (x, y)))

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

# 鼠标添加监听器
with pynput.mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()

键盘的控制与监听

import pynput

keyboard = pynput.keyboard.Controller()

keyboard.pressed(pynput.keyboard.Key.backspace)
keyboard.release(pynput.keyboard.Key.backspace)

keyboard.pressed('a')
keyboard.release('a')

keyboard.pressed('A')
keyboard.release('A')

keyboard.type("hello world!")


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


def on_release(key):
    print("{} released".format(key))
    if key == pynput.keyboard.Key.esc:
        # stop listener
        return False


# 键盘添加监听器
with pynput.keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()


你可能感兴趣的:(python,tool,pynput,键盘,鼠标,python)