CatChMeIfUCan
CatChMeIfUCan

Reputation: 569

check if all inputs has values in pysimplegui

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?

Upvotes: 2

Views: 1901

Answers (1)

Jason Yang
Jason Yang

Reputation: 13051

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()

Upvotes: 2

Related Questions