我撰寫了一個 python 程式,它截取螢屏截圖并在給定區域中查找 .PNG 影像,如果存在則單擊該圖片。我正在使用庫 pyautogui。
while keyboard.is_pressed('q') == False:
pic = pyautogui.screenshot(region=(360,158,1900,1025))
width, height = pic.size
if pyautogui.locateOnScreen('greenlightning.png', region=(360,158,1900,1025), grayscale=True, confidence=0.8) != None:
lightningloc = pyautogui.locateOnScreen('greenlightning.png')
x = lightningloc[0]
y = lightningloc[1]
pyautogui.click(x, y - 50)
time.sleep(0.2)
else:
time.sleep(0.1)
問題是它有時會拋出 TypeError,因為“x”或“y”是“NoneType”。
File "C:\****\**\***\***\****.py", line 18, in <module>
x = lightningloc[0] TypeError: 'NoneType' object is not subscriptable
我只想讓程式點擊比我的影像坐標高 50 像素的像素'greenlightning.png'。你對這個pyautogui.click()功能有什么想法嗎?
uj5u.com熱心網友回復:
我認為問題是第一次locateOnScreen()呼叫回傳坐標,但第二次呼叫回傳None。[0]inlightningloc[0]稱為下標。錯誤訊息告訴您您嘗試下標NoneType. lightningloc是被下標的變數。None是唯一型別為 的值NoneType,因此lightningloc也是None。嘗試呼叫locateOnScreen()一次并將其分配給一個變數,然后檢查None,如下所示:
lightningloc = pyautogui.locateOnScreen('greenlightning.png', region=(360,158,1900,1025), grayscale=True, confidence=0.8)
if lightningloc is not None:
x = lightningloc[0]
y = lightningloc[1]
pyautogui.click(x, y - 50)
time.sleep(0.2)
else:
time.sleep(0.1)
uj5u.com熱心網友回復:
第一次呼叫locateOnScreen()使用confidence關鍵字引數,允許模糊匹配(安裝 OpenCV 時)。第二次呼叫它時,您沒有傳遞此關鍵字引數,PyAutoGUI 正在嘗試進行像素完美匹配。第二次呼叫未能找到像素完美匹配,因此它回傳None導致稍后出現錯誤。
以下是更改代碼的方法,以便它不會對 進行兩次單獨的呼叫locateOnScreen():
while keyboard.is_pressed('q') == False:
pic = pyautogui.screenshot(region=(360,158,1900,1025))
width, height = pic.size
lightningloc = pyautogui.locateOnScreen('greenlightning.png', region=(360,158,1900,1025), grayscale=True, confidence=0.8)
if lightningloc is not None:
x = lightningloc[0]
y = lightningloc[1]
pyautogui.click(x, y - 50)
time.sleep(0.2)
else:
time.sleep(0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/445442.html
標籤:Python python-3.x 坐标 pyautogui
