0

I need to make sure user input entered in textbox with pysimplegui is integer or empty. For this I am following below method:

import PySimpleGUI as sg

sg.theme('SandyBeach')

layout = [
    [sg.Text('Please enter your Phone')],

    [sg.Text('Phone', size=(15, 1)), sg.InputText(key="lp1")],
    [sg.Button("e"), sg.Quit()]
]
window = sg.Window('Simple data entry window', layout)
while True:

    event, values = window.read()

    if event == "e":
        height = int(values['lp1'])
        print(type(height))


        if height == "" or type(height) == int:
            print("s")
        else:
            print("n")

    if event in [sg.WINDOW_CLOSED, "Quit"]:
        break


window.close()
 

The issue here is if I make height = int(values['lp1']) & leave the input blank I get ValueError:

invalid literal for int() with base 10: '223d'

if I make height = height = values['lp1'] height type is str

also the expected output should be n when string is entered. Kindly suggest how to rectify it.

1 Answer 1

4

You will get an exception if you call int with argument which is not an integer-format string.

Example code as following

import PySimpleGUI as sg

sg.theme('SandyBeach')

layout = [
    [sg.Text('Please enter your Phone')],
    [sg.Text('Phone', size=(15, 1)), sg.InputText(key="lp1")],
    [sg.Button("e"), sg.Quit()]
]
window = sg.Window('Simple data entry window', layout)
while True:

    event, values = window.read()

    if event in (sg.WINDOW_CLOSED, "Quit"):
        break
    elif event == "e":
        text = values['lp1']
        if text == '':
            print('Null string')
        else:
            try:
                value = int(text)
                print(f'Integer: {value}')
            except:
                print("Not Integer")

window.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.