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來停止監聽器。