二、python小功能記錄——監聽鼠標事件


1.原文鏈接

#-*- coding:utf-8 -*-
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)              # 滾動鼠標

## 監聽鼠標
from pynput.mouse import Listener

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

def on_scroll(x, y, dx, dy):
    # 監聽鼠標滾輪
    print('Scrolled {0}'.format((x, y)))

# 連接事件以及釋放
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()
# 一個鼠標監聽器是一個線程。線程,所有的回調將從線程調用。從任何地方調用pynput.mouse.Listener.stop,或者調用pynput.mouse.Listener.StopException或從回調中返回False來停止監聽器。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM