【问题标题】:'TypeError: 'NoneType' object is not subscriptable' in Python while statement'TypeError:'NoneType'对象不可下标'在Python while语句中
【发布时间】:2021-11-05 20:52:02
【问题描述】:

我是一个刚刚学习 Python 的初学者。

我正在使用 'pyautogui' 创建一个点击复选框的机器人。

代码按照我想要的方式运行。

但我不知道如何摆脱最后的“while”语句。

当我点击所有复选框时,我收到以下错误:

TypeError: 'NoneType' 对象不可下标

下面是我写的代码。

import pyautogui
import PIL

pyautogui.sleep(2)

while True:
    x1=pyautogui.center(pyautogui.locateOnScreen("checkbox.png", region=(50, 50, 1000, 1000), confidence=0.9)) 
    pyautogui.moveTo(x1)
    pyautogui.click()
    sftp = pyautogui.locateOnScreen("sftp.png", region=(750, 450, 500, 500), confidence=0.7)
    pyautogui.sleep(0.5)
    print(x1)
    if x1 == None:
        break
        print("work is done")

执行上面的代码,完成后,输出会是这样的:

Point(x=212, y=859)
Point(x=212, y=877)
Traceback (most recent call last):
  File "c:\project\a_\experi.py", line 7, in <module>
    x1=pyautogui.center(pyautogui.locateOnScreen("checkbox.png", region=(50, 50, 1000, 1000), confidence=0.9))
  File "c:\python39-32\lib\site-packages\pyscreeze\__init__.py", line 581, in center
    return Point(coords[0] + int(coords[2] / 2), coords[1] + int(coords[3] / 2))
TypeError: 'NoneType' object is not subscriptable

【问题讨论】:

  • 看起来你的 coords 是无类型
  • center() 不返回任何内容,它只是将屏幕截图位置居中到特定点。

标签: python pyautogui rpa


【解决方案1】:

从官方documentation of PyAutoGUI可以看出,locateOnScreen()函数在无法定位到正在搜索的图片时会抛出ImageNotFoundException并返回None为了。出现此错误的原因可能如下:

  1. 如果图像文件名有错误(必须与原始图像文件名相同)。
  2. 如果图片文件的扩展名有误(必须与原图片扩展名一致)。
  3. 如果为图像指定的像素不匹配。通常,像素(区域)应该与实际图像位置非常接近。可以尝试使用较小的置信度参数值来忽略实际图像位置与指定像素之间可忽略不计的差异。

【讨论】:

    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多