简体   繁体   中英

Update Element Using a Function - PySimpleGUI

In my application, I'm trying to update a text element by initiating a function call when a specific button is pressed. Right now, pressing the button generates an error in the console: NameError: name 'window' is not defined.

The code I'm working with is:

import PySimpleGUI as sg
sg.theme('DarkAmber')
introText = """ Let's begin!"""
landing = """ Okay"""
col1 = [[sg.Button("""Let's begin!"""), sg.Button('Win3')]]
col2 = [[sg.Button('Exit')]]
def makeWin1():
    layout = [[sg.Menu(menu_def)],
              [sg.Text(introText, font= 'Helvetica 10', justification='center', key='text1')],
              [sg.Column(col1, vertical_alignment='center', justification='center',  k='C1')],
              [sg.Column(col2, vertical_alignment='center', justification='center',  k='C2')]]
    return sg.Window('Escape From Tenopia 2', layout, finalize=True,)

def main():
    window1 = makeWin1()

    while True:
        window, event, values = sg.read_all_windows()

        if window == sg.WIN_CLOSED:
            break
        if event == sg.WIN_CLOSED or event == 'Exit':
            window.close()
            if window == window1:
                window1 = None
        if event == 'About...':
            sg.popup(introText)

        if event == """Let's begin!""":
            change1()

def change1():
    window["text1"].update(landing)

if __name__ == '__main__':
    main()

How can I make it such that pressing the "Let's Begin?" button updates the main text element to show the text in 'landing'?

You need to pass a parameter to change1():

        if event == "Let's begin!":
            change1(window1)

def change1(window):
    window["text1"].update(landing)

Or don't use any extra function for that and adjust your main() like this:

        if event == "Let's begin!":
            window1["text1"].update(landing)

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