Home > Net >  Changing pysimplegui.Combo displayed value from code, not user
Changing pysimplegui.Combo displayed value from code, not user

Time:07-16

Note: I had this question and couldn't find a good response, so I started drafting the question and then figured it out. I will post it anyway as reference (https://stackoverflow.com/help/self-answer).

Question: I am trying to create a drop-down list that whose value is saved at the press of a button (my actual application uses multiple drop-downs and a single Apply, but the answer is the same). I also want a Reset button to discard changes made since last hitting Apply. How can I go back and edit the displayed value of sg.Combo?

Example Code:

import PySimpleGUI27 as sg # NOTE: If using python3, delete '27'

if __name__ == "__main__":
    data = '' # Stored data
    layout = [
        [sg.Combo(['', 'opt1', 'opt2', 'opt3'], key='_key_'), sg.Button('Apply')],
        [sg.Button('Reset'), sg.Button('Exit')]   
    ]
    window = sg.Window('Minimum Example', layout)
    
    while True:
        event, value = window.read()
        if event == 'Exit':
            break
        elif event == 'Apply': # set 'data' to the sg.Combo value
            data = value['_key_']
        elif event == 'Reset': # set sg.Combo value to 'data'
            # This is where my question is focused.
            # How can I change the displayed drop-down back to
            # whatever is saved in 'data'?
            window['_key_'].Update(value=data) # <---- Answer
        if value is None: 
            break # Value is None, window is probably closed
        
    window.close()

TLDR: window['_key_'].Update(value=data)

CodePudding user response:

I baked the answer into the question, but I'll elaborate a little more here:

The way to update sg.Combo and other PySimpleGUI elements is with the Update() function. You can use the Update() function to go and change its attributes. For example, is you wanted to edit the value and list of a Combo element, you could use window['_key_'].Update(value=new_value, values=new_list)

Buttons have a similar function that can do stuff like change the color and text window['_key_'].Update(button_color=new_color, text=new_text)

I'm sure many other elements have a similar Update() function and they are pretty easy to find if you go to the class definition in PySimpleGUI27.py (or PySimpleGUI.py).

EDIT: For more info, reference the PySimpleGUI cookbook. <Ctrl F> and look for 'update ' (the trailing space will get you there faster).

  • Related