Pyautogui TypeError:'NoneType'对象不可迭代

GLH*_*LHF 5 python python-3.4 pyautogui

我正在尝试使用locateCenterOnScreen()PyAutoGUI的功能,但它引发了:

Traceback (most recent call last):
  File "C:\Users\windows\Desktop\asd.py", line 3, in <module>
    buttonx, buttony = pyautogui.locateCenterOnScreen('who.jpg')
TypeError: 'NoneType' object is not iterable
Run Code Online (Sandbox Code Playgroud)

我的代码是:

import pyautogui

buttonx, buttony = pyautogui.locateCenterOnScreen('who.jpg')
pyautogui.doubleClick(buttonx,buttony)
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Keo*_*zon 8

这里的Pyautogui文档中,当locCenterOnScreen无法在屏幕上找到图像时,它会返回None.

请注意,您正在寻找此方法的2个结果,但是None只是一个结果(因为该方法通常返回两个,这对我来说似乎是糟糕的设计 - 它应该引发异常,或者至少返回一个带有两个的元组)没有对象).

看看下面的例子,基本上是你发生的事情:

>>> foo,bar = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable
Run Code Online (Sandbox Code Playgroud)

在我看来,解决这个问题的最简单和最恐怖的方法就是尝试捕捉它:

try:
    buttonx,buttony = pyautogui.locateCenterOnScreen('who.jpg')
except TypeError:
    """ Do something to handle the fact that the image was not found"""
Run Code Online (Sandbox Code Playgroud)

编辑:为了回答你在评论中提出的问题,似乎对这个图书馆的工作原理或它在屏幕上发现的内容存在误解.您可以通过某些图像为库提供所需内容的表示.当图像无损时,它的效果要好得多,因为它是一个精确的,逐像素的表示.然后,库会在您的计算机屏幕上搜索所提供图像所代表的实际内容.当你提出问题时,它不会找到jpegs或pngs.它找到实际的渲染对象.因此,如果您在桌面上为网络浏览器拍摄了图标的屏幕截图,它将从该屏幕截图中找到实际图标并单击它,但前提是它是可见的.如果它在其他窗户或其他东西后面,它将找不到它.它不会在屏幕上搜索图标文件,而是搜索图标本身.因此,例如,如果您将实际的.ico文件提供给库,则如果它被另一个窗口覆盖,则无法找到该图标,即使该图标在技术上位于您的桌面上,因为它当前未呈现.

HTH