Reputation: 37
I have simple GUI with two inputs and exit button. Inputs have default_value = 0.00. I want to validate user change in the way that input can be only float format,'.2f' and <= 5.0. Example from cookbook helps partially. When I use this code:
import PySimpleGUI as sg
layout = [[sg.Input(key='first_input', enable_events=True, default_text='0.00')],
[sg.Input(key='second_input', enable_events=True, default_text='0.00')],
[sg.Button('Exit')]]
window = sg.Window('Main', layout)
while True:
event, values = window.read()
if event in ['Exit', sg.WIN_CLOSED]:
break
if event == 'first_input' and values['first_input']:
try:
in_as_float = float(values['first_input'])
if float(values['first_input']) > 5:
window['first_input'].update('5')
except:
if len(values['first_input']) == 1 and values['first_input'][0] == '-':
continue
window['first_input'].update(values['first_input'][:-1])
window.close()
But when user delete content of "first_input" and decide to fill "second_input" the previous one remains empty. How to prevent it and for example back to default value when user left input empty.
I have tried to do someting like:
if values['first_input'] == '':
window['firs_input'].update['0.00']
but this do not work because it will not let to user delete content. For example when he want to change from 3 to 4. After he delete 3 0.00 apears immediately.
Upvotes: 2
Views: 3727
Reputation: 13051
Try to validate value by regex, maybe you can test it meet all requirements.
import re
import PySimpleGUI as sg
def select(element):
element.Widget.select_range(0, 'end')
element.Widget.icursor('end')
def validate(text):
result = re.match(regex, text)
return False if result is None or result.group() != text else True
regex = "^[+-]?([0-5](\.(\d{0,2}))?)?$"
old = {'IN1':'0.00', 'IN2':'0.00'}
validate_inputs = ('IN1', 'IN2')
layout = [
[sg.Input('0.00', enable_events=True, key='IN1')],
[sg.Input('0.00', enable_events=True, key='IN2')],
[sg.Button('Exit')],
]
window = sg.Window('Title', layout, finalize=True)
select(window['IN1'])
for key in validate_inputs:
window[key].bind('<FocusIn>', ' IN')
window[key].bind('<FocusOut>', ' OUT')
while True:
event, values = window.read()
if event in ['Exit', sg.WIN_CLOSED]:
break
elif event in validate_inputs:
element, text = window[event], values[event]
if validate(text):
try:
v = float(text)
if v > 5:
element.update(old[event])
continue
except ValueError as e:
pass
old[event] = text
else:
element.update(old[event])
elif event.endswith(' IN'):
key = event.split()[0]
element, text = window[key], values[key]
select(element)
elif event.endswith(' OUT'):
key = event.split()[0]
element, text = window[key], values[key]
try:
v = float(text)
element.update(f'{v:.2f}')
except ValueError as e:
element.update('0.00')
window.close()
Upvotes: 2