简体   繁体   中英

PySimpleGUI: Get selected value in OptionMenu

Using PySimpleGUI in Python, I have a window that has an OptionMenu element, which is basically a TKinter pimped combobox. I want to retrieve the currently selected element.

Having this OptionMenu:

sg.OptionMenu(default_value ='Live',values=('Live', 'Frozen', 'Delayed'),key='-MARKETDATA-')

Typically you would use this to get the selected menu item:

print(window['-MARKETDATA-'].get())

except that the OptionMenu class does not have a.get() method.

I can get the selected menu item by using:

event2, values2 = window.Read(timeout=1)
print(values2['-MARKETDATA-'])

but that hardly seems elegant. Is there another more straightforward way that I overlooked?

There's no option enable_events in sg.OptionMenu , and also no method get defined. Here I enable event for it by trace and also get selected value by values[key] .

import PySimpleGUI as sg


def callback(var, index, mode):
    """
    For OptionMenu
    var - tkinter control variable.
    index - index of var, '' if var is not a list.
    mode - 'w' for 'write' here.
    """
    window.write_event_value("Language", window['Language'].TKStringVar.get())

sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 16))

data = ["Arabic", "Chinese", "English", "German", "Japanese", "Latin", "Spanish"]

layout = [
    [sg.OptionMenu(data, default_value=data[2], key='Language')],
    [sg.Button("Click")],
]

window = sg.Window('Title', layout, finalize=True)
window['Language'].TKStringVar.trace("w", callback)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'Language':
        print(event, values['Language'])
    elif event == 'Click':
        print(event, values['Language'])

window.close()

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