I have a window that has multiple inputs and combo selectbox like this
main_layout = [[sg.Text('First Name', size=(15, 1)),
sg.InputText(key='gname', size=(25, 1))],
[sg.Text('V Type', size=(15, 1)),
sg.Combo(['option 1','option 2','option 3'],key="vtype",size=(25, 1)],
[sg.Text('Last Name', size=(15, 1)),
sg.InputText(key='glastname', size=(25, 1)],
[sg.Submit('Submit'),sg.Cancel('Cancel')]]
layout = [[sg.Column(main_layout,scrollable=True,vertical_scroll_only=True, size=(755,500))]]
window = sg.Window('Form', layout, font='arial',resizable=True, element_justification='l',size=(755,500))
event, values = window.read()
if event == 'Cancel' or event == sg.WIN_CLOSED:
sys.exit()
name_check = window['gname'].get().strip()
if name_check == '':
sg.popup(f"Field is Required")
window.close()
I'm already using name_check = window['gname'].get().strip() for the name event that checks it isn't blank what I want to do is on clicking submit check all inputs to have a value and not to be blank because the code above is a form and the form is long I only wrote few of them for example
The form data will be written into a text file with a regular expression and if the value would be blank the app crashes, so I want something that I can check multiple event keys at once
How can I do that?
Using window.key_dict to get a dictionary with all key:element pairs for all elements, then iterate each item to confirm if it is sg.Input element, and all inputs are not null string.
import PySimpleGUI as sg
sg.theme("DarkBlue3")
sg.set_options(font=("Courier New", 12))
layout = [
[sg.Text(f"Line {i: >2d}:"), sg.Input("")] for i in range(10)] + [
[sg.Button("Submit")],
[sg.StatusBar("", size=(20, 1), key='Status')]
]
window = sg.Window('Title', layout, finalize=True)
prompt = window['Status'].update
input_key_list = [key for key, value in window.key_dict.items()
if isinstance(value, sg.Input)]
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == "Submit":
if all(map(str.strip, [values[key] for key in input_key_list])):
prompt("All inputs are OK !")
else:
prompt("Some inputs missed !")
window.close()
Related
I created a dictionary with two keys, when selecting one of the keys, the dictionary items are updated, the problem is that I am not returning the selected value within the updated list.
for example, when selecting 'male', and then 'Executed', I would like to receive 'Executed' as a value
import PySimpleGUI as sg
genero = {
'male': ['Required','Executed'],
'female': ['Required', 'Performed']
}
layout = [
[sg.Radio('male', "RADIO1", default=False, key="-IN1-")],
[sg.Radio('female', "RADIO1", default=False, key="-IN2-")],
[sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')],
[sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")]
]
window = sg.Window("GENERATE PETITION", layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Exit":
break
elif values["-IN1-"] == True:
window['-PART-'].update(genero['male'])
elif values["-IN2-"] == True:
window['-PART-'].update(genero['female'])
elif event == 'GENERATE':
print('-PART-')
window.close()
print(event,values)
atualmente está retornando assim: Exit {'-IN1-': True, '-IN2-': False, '-PART-': []}
There's programming logic issue in the event loop, it will be better for all the cases starts with the event decision, not the value(s) decision. In your code, the case for the event GENERATE will be never executed after any one of the Radio element clicked.
import PySimpleGUI as sg
genero = {
'male': ['Required','Executed'],
'female': ['Required', 'Performed']
}
layout = [
[sg.Radio('male', "RADIO1", default=False, enable_events=True, key="-IN1-")],
[sg.Radio('female', "RADIO1", default=False, enable_events=True, key="-IN2-")],
[sg.Listbox(genero.keys(), size=(30, 3), enable_events=True, key='-PART-')],
[sg.Push(),sg.Button('GENERATE'), sg.Exit("Exit")]
]
window = sg.Window("GENERATE PETITION", layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == "Exit":
break
elif event in ('-IN1-', '-IN2-'):
if values["-IN1-"] == True:
window['-PART-'].update(genero['male'])
else:
window['-PART-'].update(genero['female'])
elif event == 'GENERATE':
selections = values['-PART-']
if selections:
print(selections[0])
else:
print('Nothing selected !')
window.close()
I want to create a progress bar using PySimpleGUI but I want the user to put the maximum of the progress bar.
this is my code:
import PySimpleGUI as sg
import random, time
sg.theme("LightBlue")
progress_value=input()
layout = [[sg.Text("Enter a number out of 50", font='Lucida'),
sg.InputText(key='-PROGRESS_VALUE-', font='Lucida, 20', size=(20, 40))],
[sg.ProgressBar(progress_value, orientation='h', size=(100, 20), border_width=4, key='-PROGRESS_BAR-',
bar_color=("Blue", "Yellow"))],
[sg.Button('Change Progress'), sg.Exit(),sg.Button('Stop Progress')]]
window = sg.Window("Progress Bar", layout)
while True:
event, values = window.read()
if event == 'Exit' or event == sg.WIN_CLOSED:
break
progress_value = int(values['-PROGRESS_VALUE-'])
if event == "Change Progress":
for i in range(progress_value):
event, values = window.read(1000)
if event == "Stop Progress":
window['-PROGRESS_BAR-'].update(i-1)
break
window['-PROGRESS_BAR-'].update(max=progress_value)
window['-PROGRESS_BAR-'].update(i+1)
window.close()
as you can see the maximum which is "progress_value" is given by an input (progress_value=input())
but i want it to come from the input text of the user (sg.InputText(key='-PROGRESS_VALUE-', font='Lucida, 20', size=(20, 40))) and that value will be set to progress_value
Here's one way of doing what you're after using a single event loop
When changing the max value of a ProgressBar, you must set a current value too (in the same update call).
import PySimpleGUI as sg
sg.theme("LightBlue")
progress_value = 50
layout = [[sg.Text("Enter a number out of 50", font='Lucida'),
sg.InputText(key='-PROGRESS_VALUE-', font='Lucida, 20', size=(20, 40))],
[sg.ProgressBar(progress_value, orientation='h', size=(100, 20), border_width=4, key='-PROGRESS_BAR-',
bar_color=("Blue", "Yellow"))],
[sg.Button('Change Progress'), sg.Button('Start Progress'), sg.Button('Stop Progress')]]
window = sg.Window("Progress Bar", layout)
progress_started, counter, timeout = False, 0, None
while True:
event, values = window.read(timeout=timeout)
if event == 'Exit' or event == sg.WIN_CLOSED:
break
if event == "Change Progress":
progress_value = int(values['-PROGRESS_VALUE-'])
# NOTE - must set a current count when changing the max value
window['-PROGRESS_BAR-'].update(current_count= 0, max=progress_value)
elif event == 'Start Progress':
progress_started = True
counter = 0
timeout = 1000
elif event == 'Stop Progress':
progress_started = False
timeout = None
if progress_started:
window['-PROGRESS_BAR-'].update(counter)
counter += 1
if counter > progress_value:
progress_started = False
window.close()
I'd like to write a GUI with PySimpleGUI that can be used entirely by keyboard. Based on the following sample code:
import PySimpleGUI as sg
layout = [[sg.Text("Hello from PySimpleGUI")], [sg.Button(button_text="OK")]]
window = sg.Window("Demo", layout)
while True:
event, values = window.read()
if event == "OK" or event == sg.WIN_CLOSED:
break
window.close()
How can I add a hotkey which I can press using Alt+O to press the OK-Button? The O on the OK-Button should be underlined:
A minimalist working example derived from: https://github.com/PySimpleGUI/PySimpleGUI/issues/4122
import PySimpleGUI as sg
layout = [
[sg.Button("ok", size=(10, 2), key='button1'),
sg.Button("exit", size=(10, 2), key='button2')],
]
window = sg.Window('Hotkeys', layout, use_default_focus=False, finalize=True)
button1, button2 = window['button1'], window['button2']
window.bind("<Alt_L><o>", "ALT-o")
window.bind("<Alt_L><x>", "ALT-x")
button1.Widget.configure(underline=0, takefocus=0)
button2.Widget.configure(underline=1, takefocus=0)
while True:
event, values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event in ("button1", "ALT-o"):
print('OK')
elif event in ("button2", "ALT-x"):
break
window.close()
I am using PySimpleGUI to build a GUI for my application. I am trying to print out on screen some messages for the user through a Listbox but when I call the window[].update() lines the print out is not showing by line but putting each character on a new line. I am not sure if Listbox is the function that I should be using or if there is another function better suited for what I want to do.
import PySimpleGUI as sg
import os, sys
file_list_column = [
[sg.Text('File Name: '), sg.In(size = (25, 1), enable_events = True, key = '-ID-')],
[sg.Text('File Location: '), sg.In(size = (25, 1), enable_events = True, key = '-FOLDER-'),sg.FolderBrowse()],
[sg.Button('Create Location')],
[sg.Listbox(values = [], enable_events = True, size = (40, 20), key = '-UPDATES-')],]
layout = [[sg.Column(file_list_column)],
[sg.Button('Close')]]
window = sg.Window('Test', layout)
while True:
event, values = window.read()
if event == 'Close' or event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Create Location':
try:
os.makedirs(os.path.join(values['-FOLDER-'], values['-ID-']))
window['-UPDATES-'].update(str('Folder location created.'))
except:
window['-UPDATES-'].update(str('Folder location NOT created.'))
window.close()
The string I want to display to the user is placing each character on its own line.
I have 2 columns and I want to reveal them on a button press by using the visibility parameter. However, it seems that columns that go from invisible to visible stop being next to each other and are instead arranged like rows.
Here is the code without the reveal, and the columns work fine:
import PySimpleGUI as sg
left_col = sg.Column([[sg.Frame('',[],background_color = '#FF0000',size = (60,40))]])
right_col = sg.Column([[sg.Frame('',[],background_color = '#00FF00',size = (60,40))]])
layout = [
[sg.Button('reveal')],
[left_col,right_col]]
window = sg.Window('Converter', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
window.close()
And here is the same code with the columns being revealed:
import PySimpleGUI as sg
left_col = sg.Column([[sg.Frame('',[],background_color = '#FF0000',size = (60,40))]],visible = False, key = 'left')
right_col = sg.Column([[sg.Frame('',[],background_color = '#00FF00',size = (60,40))]],visible = False, key = 'right')
layout = [
[sg.Button('reveal')],
[left_col,right_col]]
window = sg.Window('Converter', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
if event == 'reveal':
window['left'].update(visible = True)
window['right'].update(visible = True)
window.close()
I guess my question is whether there is a workaround for this (or whether I did something wrong).
Elements after visible=False will miss it's location in the window, so use function pin to keep the location for element if you want to set it to be invisible.
layout = [
[sg.Button('reveal')],
[sg.pin(left_col), sg.pin(right_col)]]
By default, the background is the background color of theme. Of course, you can built one by yourself which with one more option bg as background_color.
Don't forget to set the background color of the Column in your layout at the same time.
def pin(elem, vertical_alignment=None, shrink=True, expand_x=None, expand_y=None, bg=None):
if shrink:
return sg.Column([[elem, sg.Column([[]], pad=(0,0), background_color=bg)]], background_color=bg, pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y)
else:
return sg.Column([[elem]], pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y, background_color=bg)
Then you code maybe something like this
import PySimpleGUI as sg
def pin(elem, vertical_alignment=None, shrink=True, expand_x=None, expand_y=None, bg=None):
if shrink:
return sg.Column([[elem, sg.Column([[]], pad=(0,0), background_color=bg)]], background_color=bg, pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y)
else:
return sg.Column([[elem]], pad=(0, 0), vertical_alignment=vertical_alignment, expand_x=expand_x, expand_y=expand_y, background_color=bg)
left_col = sg.Column([[sg.Frame('', [], background_color = '#FF0000', size = (60,40))]], background_color='blue')
right_col = sg.Column([[sg.Frame('', [], background_color = '#00FF00', size = (60,40))]], background_color='blue')
layout = [
[sg.Button('reveal')],
[pin(left_col, bg='blue'), pin(right_col, bg='blue')]]
window = sg.Window('Converter', layout, background_color='blue')
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
window.close()