我正在尝试让我的 Python 代码在条件不匹配时单击按钮

I'm trying to get my Python Code to click on a button if a condition isn't matched

目前是满足条件才点击。

例如:

代码在我的屏幕上查找特定的单词。它与我已经定义的一组数据相匹配。

它应该如何工作:

发生了什么:

示例输出:

第三个"No common elements",不应该发生。第二次点击后出现 cookie 一词。访问 if-else 条件的方式有问题。想法?

代码如下:

import pytesseract
import numpy as nm
import winsound
import pyautogui
import time
from PIL import ImageGrab

def imToString():
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
    while (True):

        source = [
"chocolate", "muffin", "cookie"
                 ]

        cap = ImageGrab.grab(bbox=(748, 626, 916, 646))

        tesstr = pytesseract.image_to_string(
            cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
            lang='eng')

        split_words =tesstr.split()

        normalized_input = [word.rstrip('.,!?').lower() for word in split_words]
        source_normalized = [word.lower() for word in source]

        set_a = set(source_normalized)
        set_b = set(normalized_input)
        match = set_a & set_b

        if match:
            print(match)
            frequency = 2500  # Set Frequency To 2500 Hertz
            duration = 1000  # Set Duration To 1000 ms == 1 second
            winsound.Beep(frequency, duration)
            return False
        else:
            print("No common elements")
            time.sleep(1)
            pyautogui.moveTo(826,309)
            pyautogui.click()


imToString()

任何关于我犯了什么错误的意见?

我猜问题出在这里:

if match:
    print(match)
    frequency = 2500  # Set Frequency To 2500 Hertz
    duration = 1000  # Set Duration To 1000 ms == 1 second
    winsound.Beep(frequency, duration)
    # the while true stops here, you don't have the time to see the answer
    return False

也许添加:

input("Press Enter to continue...")

在 return.

之前

我清理了代码,并使用 any() 函数检查 if-else 块。代码现在按预期工作。