验证输入值 - PySimpleGUI
Validating Input Value - PySimpleGUI
我有一个带有两个输入和退出按钮的简单 GUI。输入 default_value = 0.00。我想以输入只能是浮点格式、'.2f' 和 <= 5.0 的方式验证用户更改。食谱中的示例有部分帮助。当我使用此代码时:
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()
但是当用户删除“first_input”的内容并决定填充“second_input”时,前一个仍然是空的。如何防止它,例如当用户将输入留空时返回默认值。
我试过做这样的事情:
if values['first_input'] == '':
window['firs_input'].update['0.00']
但这不起作用,因为它不会让用户删除内容。比如当他想从3改成4时,他马上删除了3个0.00 apears。
尝试通过正则表达式验证值,也许您可以测试它是否满足所有要求。
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()
我有一个带有两个输入和退出按钮的简单 GUI。输入 default_value = 0.00。我想以输入只能是浮点格式、'.2f' 和 <= 5.0 的方式验证用户更改。食谱中的示例有部分帮助。当我使用此代码时:
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()
但是当用户删除“first_input”的内容并决定填充“second_input”时,前一个仍然是空的。如何防止它,例如当用户将输入留空时返回默认值。
我试过做这样的事情:
if values['first_input'] == '':
window['firs_input'].update['0.00']
但这不起作用,因为它不会让用户删除内容。比如当他想从3改成4时,他马上删除了3个0.00 apears。
尝试通过正则表达式验证值,也许您可以测试它是否满足所有要求。
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()