繁体   English   中英

我正在尝试在 python 中使用其 function 之外的变量

[英]I'm trying to use a variable outside of its function in python

我不确定如何让我的 ans_label 访问我的 ans_string,因为它是在 function ssInterpret() 中定义的。

def ssInterpret():
    #region=(x, y, width, height)
    time.sleep(5)
    myScreenshot = pyautogui.screenshot(region=(400, 320, 800, 500))
    myScreenshot.save(imgPath)

    #reads the image

    img = cv2.imread(imgPath)
    text = pytesseract.image_to_string(img)

    q = text

    #completes the answer search

    results = brainlypy.search(q)
    question = results.questions[0]
    print('URL: '+'https://brainly.com/task/'+str(question.databaseid))
    print('QUESTION:',question)
    print('ANSWER 1:', question.answers[0])
    if question.answers_count == 2:
        print('ANSWER 2:', question.answers[1])

    ans_string = str(question.answers[0])

answer_label = Label(root, text=ans_string)

首先,你的function需要返回答案:

def ssInterpret():
    ...  # most of function elided.
    return ans_string

#then call the function 
ans = ssInterpret()
answer_label = Label(root, text=ans)

在代码顶部将ans_string初始化为ans_string = "" 然后在 function ssInterpret()内的ans_string = str(question.answers[0])之前添加一行global ans_string answer_label = Label(root, text=ans_string) ) 之前调用ssInterpret() ) 。 您的代码现在应该可以按预期工作。

修改后的完整代码:

ans_string = ""

def ssInterpret():
    #region=(x, y, width, height)
    time.sleep(5)
    myScreenshot = pyautogui.screenshot(region=(400, 320, 800, 500))
    myScreenshot.save(imgPath)

    #reads the image

    img = cv2.imread(imgPath)
    text = pytesseract.image_to_string(img)

    q = text

    #completes the answer search

    results = brainlypy.search(q)
    question = results.questions[0]
    print('URL: '+'https://brainly.com/task/'+str(question.databaseid))
    print('QUESTION:',question)
    print('ANSWER 1:', question.answers[0])
    if question.answers_count == 2:
        print('ANSWER 2:', question.answers[1])

    global ans_string
    ans_string = str(question.answers[0])

ssInterpret()
answer_label = Label(root, text=ans_string)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM