日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

用Python實現控制電腦鼠標_python

作者:風吹落葉花飄蕩 ? 更新時間: 2022-04-03 編程語言

一、序言

使用python控制按鍵無疑非常重要的技能,特別是結合機器視覺更是能發揮出超強的實力!

二、配置環境

1.下載pyautogui包

pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple/

注:如果有可能,可以在pycharm中進行以下Python控制的鼠標和鍵盤的測試與學習。

二、鼠標控制

注:由于這部分功能我不能通過截屏來顯著表現出來,在程序運行結果就不截屏了,保持界面整潔

1、獲取鼠標位置函數以及測試源碼

#獲取鼠標位置
import pyautogui as pg           #沒別的作用就單純換個名字
try:
    while True:
        x,y=pg.position()        #核心函數pg.position()
        print(str(x)+" "+str(y)) #輸出鼠標的x,y
        
except KeyboardInterrupt:
    print("\n")

程序功能:

實時輸出當前鼠標位置

核心函數:

函數名 功能
pyautogui .position() 返回當前鼠標的x,y坐標。

核心代碼:

換名:第2行 import pyautogui as pg輸出鼠標位置:第5~6行
x,y=pg.position() #核心函數pg.position()
print(str(x)+" "+str(y)) #輸出鼠標的x,y

2、控制鼠標左擊/右擊/雙擊函數以及測試源碼

# 獲取鼠標位置
import pyautogui as pg

try:
    while True:
        x, y = pg.position()
        print(str(x) + " " + str(y))  #輸出鼠標位置

        if 1746 < x < 1800 and 2 < y < 33:
            pg.click()#左鍵單擊
        if 1200 < x < 1270 and 600 < y < 620:
            pg.click(button='right')#右鍵單擊
        if 1646 < x < 1700 and 2 < y < 33:
            pg.doubleClick()#左鍵雙擊

except KeyboardInterrupt:
    print("\n")

a.程序功能
在輸出鼠標位置的基礎,分別設置了三個區域,當鼠標達到這三個區域時候,進行左鍵單擊、右鍵單擊,左鍵雙擊。

b.核心函數

函數名 功能
pyautogui.click() 鼠標左鍵單擊
pyautogui.click(button=‘right’) 鼠標右鍵單擊
pyautogui.doubleClick() 鼠標左鍵雙擊

c.核心代碼
1、觸發某事件就控制鼠標點擊:第9~14行
注:click()函數默認:button=‘left’

3、控制鼠標移動/拖動

# 3、控制鼠標移動/拖動demo
import pyautogui as pg

try:
    while True:
        x, y = pg.position()
        print(str(x) + " " + str(y))  #輸出鼠標位置
        #實現鼠標絕對移動功能
        if 1011 < x < 1357 and 320 < y < 527:
            pg.moveTo(1750, 20, 2)#花2s從當前位置移動到(1750,20)
            pg.click()  # 左鍵單擊
            
        #實現鼠標相對移動功能
        if 600 < x < 1000 and 305 < y < 425:
            pg.move(0, 200)  # 基于當前位置瞬間向下移動200像素
            
        #實現鼠標拖動功能
        if 1142<x<1391 and y<25:
            pg.dragTo(300, 400, 2, button='left') #花2s從當前位置拖到(300,400)

except KeyboardInterrupt:
    print("\n")

a.程序功能
在輸出鼠標位置的基礎,分別設置了三個區域,當鼠標達到這三個區域時候,分別進行絕對移動,相對移動,鼠標拖動三個運行演示。
注:在運行代碼全,將Pycharm全屏演示效果更好哦

b.核心函數

函數名 功能
pyautogui.moveTo() 鼠標絕對移動
pyautogui.move() 鼠標相對移動
pyautogui.dragTo() 鼠標絕對拖動

c.核心代碼
1、觸發某事件就控制鼠標移動/拖動:第9~19行
注:click()函數默認:button=‘left’

4、控制鼠標滾輪滾動

import pyautogui as pg
# 執行鼠標滾輪的滾動。垂直滾動還是水平滾動取決于底層操作系統。
pg.scroll(100)  # scroll up 50 "clicks"

注:是的就兩行,如果你是放在上面中使用,應該算只要一行就可以實現了。

總結

原文鏈接:https://blog.csdn.net/qq_51116518/article/details/122571094

欄目分類
最近更新