python鼠标键盘同时监听

from pynput.mouse import Listener as Listener_mouse
from pynput.keyboard import Listener as Listener_keyboard
from pynput.mouse import Button
from pynput.keyboard import Key
list = []

class Mouse():
    def on_press(key):
        print('{0} 按下'.format(key))
        list.append('{0} 按下'.format(key))
    # 释放键盘时回调的函数
    def on_release(key):
        print('{0} 松开'.format(key))
        list.append('{0} 松开'.format(key))
        if key == Key.esc:
            # 停止监听
            with open("shop.txt","w+") as f:
                f.write(str(list))
            return False

    Listener_keyboard = Listener_keyboard(on_press=on_press, on_release=on_release)

    Listener_keyboard.start()
    def on_move(x, y):
        print('鼠标指针移动到的位置 {0}'.format((x, y)))
        list.append((x, y))
    # 监听鼠标按键
    # on_click(x, y, button, pressed)是鼠标点击时回调的函数
    # 四个参数x,y,button,pressed。
    # x,y描述的是鼠标点击的位置
    # button是鼠标的按键,值有三种Button.left(左键)、Button.right(右键)、Button.middle(中键)
    # 注意鼠标button使用按下一次会有两次反馈(按下和松开)。想要使用一次可以把一个if pressed:语句放在它的外层
    # pressed的值是bool类型是鼠标按键的按下时是True,松开时为False。
    def on_click(x, y, button, pressed):
        if button == Button.left:
            print('{0}位置{1}'.format('鼠标左键按下' if pressed else '鼠标左键松开', (x, y)))
            list.append('{0}位置{1}'.format('鼠标左键按下' if pressed else '鼠标左键松开', (x, y)))
        elif button == Button.right:
            print('{0}位置{1}'.format('鼠标右键按下' if pressed else '鼠标右键松开', (x, y)))
            list.append('{0}位置{1}'.format('鼠标右键按下' if pressed else '鼠标右键松开', (x, y)))
        elif button == Button.middle:  # 停止监听
            return False
    # 滑轮滚动事件
    # x,y指针位置
    # dx,dy滚轮的动作方向
    def on_scroll(x, y, dx, dy):
        print('Scrolled {0}'.format((x, y)))
        list.append('滚轮滑动 {0}'.format((x, y)))
        print(dx, dy)

    Listener_mouse = Listener_mouse(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
    Listener_mouse.start()
    # with Listener_mouse(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as Listener_mouse:
    #     pass
    Listener_keyboard.join()

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