Python3“如果”没有捕捉到它正在检查的东西

2024-09-29 23:31:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经回顾了其他问题,比如(Python 'if x is None' not catching NoneType),但我没有发现这些信息对我的场景有用。你知道吗

    import pyautogui

##########################
#This is a looping routine to search for the current image and return its coordinates 
##########################

def finder(passedImage, workSpace): #start the finder func
    print (passedImage) #print the image to be found
    currentImage = pyautogui.locateOnScreen(passedImage,region=(workSpace),  grayscale=True) #search for the image on the screen
    if currentImage == None: # if that initial search goes "none" ...
        print ("Looking") #Let us know we are looking
        finder(passedImage,workSpace) #go and do the function again
    print(currentImage) #print out the coordinates
    currentImageX, currentImageY = pyautogui.center(currentImage) #get the X and Y coord
    pyautogui.click(currentImageX, currentImageY) #use the X and Y coords for where to click
    print(currentImageX, currentImageY) #print the X and Y coords

剧本的构思很简单。只需找到图像的坐标,然后使用pyautogui库(module?新术语)

除了“if currentImage==None:”位之外,它都可以工作。你知道吗

有时当currentImage为None时,它会捕捉到,然后适当地重新运行函数以获取它,但有时它不会。我似乎找不到任何押韵或原因在它后面,有时有效,有时无效。你知道吗

任何关于我如何检查无然后回应无的建议都是很好的:)

引发的错误示例如下:

Traceback (most recent call last):
File "fsr_main_001.py", line 57, in <module>
newItem()
File "fsr_main_001.py", line 14, in newItem
finder.finder(passedImage,workSpace)
File "/home/tvorac/python/formAutomation/finder.py", line 14, in finder
currentImageX, currentImageY = pyautogui.center(currentImage) #get the X and Y coord
File "/usr/local/lib/python3.5/dist-packages/pyscreeze/__init__.py", line 398, in center
return (coords[0] + int(coords[2] / 2), coords[1] + int(coords[3] / 2))
TypeError: 'NoneType' object is not subscriptable

Tags: andthepynoneiffindercoordsworkspace
1条回答
网友
1楼 · 发布于 2024-09-29 23:31:42

我认为发生的事情是,当你说你在运行这个函数时,你是在递归地这样做。对finder的新调用后没有return

if currentImage == None: # if that initial search goes "none" ...
    print ("Looking") #Let us know we are looking
    finder(passedImage,workSpace) #go and do the function again
print(currentImage) #print out the coordinates

一旦finder()调用完成了它的工作,控制返回到函数的实例,其中currentImageNone,它继续打印,pyautogui.center等等。你知道吗

考虑到这可能会导致一些相当深的递归,这可能不是找到图像的最佳方法。相反,某种形式的循环是最好的。你知道吗

currentImage = None
while currentImage is None:
    currentImage = pyautogui.locateOnScreen(passedImage,region=(workSpace), grayscale=True) #search for the image on the screen

(或类似的,添加了超时、最大重试次数等)

相关问题 更多 >

    热门问题