【问题标题】:Python3 "If" not catching what it is checkingPython3“如果”没有捕捉到它正在检查的内容
【发布时间】:2016-10-07 14:12:09
【问题描述】:

我查看了其他问题,例如 (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 库(模块?对我来说是新术语)点击它

除了“if currentImage == None:”位之外,这一切都有效。

它有时会在 currentImage 为 None 时捕获,然后适当地重新运行该函数以获取它,但有时它不会。我似乎找不到它背后的任何韵律或原因,有时有效,有时则无效。

任何关于我如何检查 None 然后回应 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

【问题讨论】:

  • 再次递归调用查找器不会改变递归返回​​时 currentImage 为 None 的事实。

标签: python typeerror nonetype pyautogui


【解决方案1】:

我认为正在发生的事情是,当您说要重新运行该函数时,您是在递归执行此操作。新呼叫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

(或类似的东西,增加超时、最大重试次数等)

【讨论】:

    猜你喜欢
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多