python - 验证输入值 - 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()
推荐阅读
- java - 如何从 Android Studio 生成 jacoco 报告并将其导出到 sonarqube,因为代码覆盖率为零(jacoco+gradle+sonarqube)
- python - “AttributeError:‘str’对象没有属性‘coord’——气候建模和编码问题
- c - isalnum() 如何在 C 中获得他的返回值?
- python-sphinx - 重组文本在页面之间拆分段落并添加错误的列表项目符号
- c - 在 malloc 之前声明指针有什么区别
- html - 如何在选项卡中添加选项卡,使用 Bootstrap 的内部选项卡
- java - 关于将if语句放入java数组
- c++ - 楼梯问题.. 为什么我的代码不适用于 n>21
- .net - 使用表达式将 X 或 Y 替换为 J 或 Q
- c# - CSHTML 所见即所得编辑器/预览器