如何在IF中使用result吐出True/False?
How to use result in IF to spit out True/False?
以下代码片段
if pyautogui.locateOnScreen('test4x4.png', region = (200,200,4,4)) == "Box(left=200, top=200, width=4, height=4)":
print("Found")
else:
print("NotFound")
吐出NotFound
,
但是
print(pyautogui.locateOnScreen('test4x4.png', region = (200,200,4,4)))
打印出“Box(left=200, top=200, width=4, height=4)”。
如何正确匹配结果以便取回 Found 值?
locateOnScreen
函数returns一个pyscreeze.Box
对象,不是一个字符串。
因此在进行任何比较之前,您需要将其转换为元组:
box = pyautogui.locateOnScreen('test4x4.png', region = (200,200,4,4))
if box is not None and tuple(box) == (200, 200, 4, 4):
print("Found")
else:
print("NotFound")
<编辑>
您得到 TypeError: 'NoneType' object is not iterable
的原因是,如果找不到图像,locateOnScreen
returns None
。尝试将 None
转换为元组:tuple(None)
会引发错误。
您可以通过勾选不是 None
的框来防止出现这种情况,正如我在上面编辑的那样。
我无法解释为什么在成功找到图像后您仍然收到错误消息,因此您需要提供更多信息以便我们解决该问题。
您的版本不起作用的原因是当您调用 print(box)
时,print
函数在幕后实际上调用 str(box)
并打印它。
这就是为什么
>>> print(box)
Box(left=200, top=200, width=4, height=4)
它不意味着
box == "Box(left=200, top=200, width=4, height=4)"
以下代码片段
if pyautogui.locateOnScreen('test4x4.png', region = (200,200,4,4)) == "Box(left=200, top=200, width=4, height=4)":
print("Found")
else:
print("NotFound")
吐出NotFound
,
但是
print(pyautogui.locateOnScreen('test4x4.png', region = (200,200,4,4)))
打印出“Box(left=200, top=200, width=4, height=4)”。 如何正确匹配结果以便取回 Found 值?
locateOnScreen
函数returns一个pyscreeze.Box
对象,不是一个字符串。
因此在进行任何比较之前,您需要将其转换为元组:
box = pyautogui.locateOnScreen('test4x4.png', region = (200,200,4,4))
if box is not None and tuple(box) == (200, 200, 4, 4):
print("Found")
else:
print("NotFound")
<编辑>
您得到 TypeError: 'NoneType' object is not iterable
的原因是,如果找不到图像,locateOnScreen
returns None
。尝试将 None
转换为元组:tuple(None)
会引发错误。
您可以通过勾选不是 None
的框来防止出现这种情况,正如我在上面编辑的那样。
我无法解释为什么在成功找到图像后您仍然收到错误消息,因此您需要提供更多信息以便我们解决该问题。
您的版本不起作用的原因是当您调用 print(box)
时,print
函数在幕后实际上调用 str(box)
并打印它。
这就是为什么
>>> print(box)
Box(left=200, top=200, width=4, height=4)
它不意味着
box == "Box(left=200, top=200, width=4, height=4)"