Reputation: 83
For a project I am working on, I want to make a pop-up window with several different choices, that can return a value based on which choice the user picks; I found solutions to get simple pop-ups, but not ones that return a value. I am using Python 3.8.
Upvotes: 6
Views: 14174
Reputation: 6826
PySimpleGui is the way to go for simplicity - and it seems to work with Python 3.8.3 on Windows 10.
Creating a simple gui dialog to make a selection can't get much easier than this (although it can also do much more complex UI when needed):
import PySimpleGUI as sg
#sg.theme('DarkAmber') # Add a touch of color
options = ['Option a','Option b','Option c']
# All the stuff inside your window.
layout = [
[sg.Text('Select one->'), sg.Listbox(options,select_mode=sg.LISTBOX_SELECT_MODE_SINGLE,size=(20,len(options)))],
[sg.Button('Ok'), sg.Button('Cancel')]
]
# Create the Window
window = sg.Window('Make your choice', layout)
# Event Loop to process "events" and get the "values" of the input
while True:
event, values = window.read()
print( f"event={event}" )
if event is None or event == 'Ok' or event == 'Cancel': # if user closes window or clicks cancel
break
# close the window
window.close()
if event == "Cancel":
print( "You cancelled" )
else:
print('You entered ', values[0])
sg.popup( f"You selected {values[0]}" )
Upvotes: 1
Reputation: 5754
As barny suggested, PySimpleGUI is about as easy as it gets.
What you've described is what's called a one-shot window in the PySimpleGUI Cookbook.
These types of GUIs can be written as a single line of PySimpleGUI code because you don't need a full event loop.
import PySimpleGUI as sg
event, values = sg.Window('Choose an option', [[sg.Text('Select one->'), sg.Listbox(['Option a', 'Option b', 'Option c'], size=(20, 3), key='LB')],
[sg.Button('Ok'), sg.Button('Cancel')]]).read(close=True)
if event == 'Ok':
sg.popup(f'You chose {values["LB"][0]}')
else:
sg.popup_cancel('User aborted')
After the call to Window, with the chained read
call, you're provided the event used to close the window (which button or if closed with the "X") and the dictionary of values. In this case, your values dictionary will have a single item values['LB']
. For Listboxes, this value will be a list. To get the item chosen, you could reference values['LB'][0]
Upvotes: 3