简体   繁体   中英

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

I'm not sure how I could get my ans_label to access my ans_string as it is defined within the 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)

First, your function needs to return the answer:

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

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

Initialize ans_string as ans_string = "" at the top of your code. Then add a line global ans_string prior to ans_string = str(question.answers[0]) inside the function ssInterpret() . Call ssInterpret() before answer_label = Label(root, text=ans_string) . Your code should now work as expected.

Complete code with modification:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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