You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySimpleGUI输入框未输入/输入错误时弹窗提示实现方法

用PySimpleGUI实现输入验证需求

下面是针对你需求的完整实现代码,包含两种输入验证逻辑:

import PySimpleGUI as sg

# 布局设计
layout = [
    [sg.Text("请输入数字:"), sg.Input(key="-NUM_INPUT-"), sg.Button("确认数字", key="-CONFIRM_NUM-")],
    [sg.Text("土地面积:"), sg.Input(key="-AREA_INPUT-"), sg.Button("Hectare(公顷)", key="-HECTARE-"), sg.Button("Acre(英亩)", key="-ACRE-")],
    [sg.Button("退出")]
]

window = sg.Window("输入验证示例", layout)

while True:
    event, values = window.read()
    
    if event == sg.WIN_CLOSED or event == "退出":
        break
    
    # 处理数字输入验证
    if event == "-CONFIRM_NUM-":
        num_input = values["-NUM_INPUT-"].strip()
        # 检查空值
        if not num_input:
            sg.popup_error("请输入数字内容!")
            continue
        # 检查类型是否正确
        try:
            num = float(num_input)
            sg.popup(f"输入的数字是:{num}")
        except ValueError:
            sg.popup_error("输入类型错误,请输入有效的数字!")
    
    # 处理土地面积按钮的空值验证
    if event in ("-HECTARE-", "-ACRE-"):
        area_input = values["-AREA_INPUT-"].strip()
        if not area_input:
            sg.popup_error("请先输入土地面积!")
            continue
        # 可添加单位转换逻辑,示例如下
        try:
            area = float(area_input)
            if event == "-HECTARE-":
                # 示例:输入值为平方米,转换为公顷(1公顷=10000平方米)
                hectare = area / 10000
                sg.popup(f"转换为公顷:{hectare:.2f} 公顷")
            else:
                # 示例:输入值为平方米,转换为英亩(1英亩≈4046.86平方米)
                acre = area / 4046.86
                sg.popup(f"转换为英亩:{acre:.2f} 英亩")
        except ValueError:
            sg.popup_error("面积输入无效,请输入数字!")

window.close()

关键逻辑说明:

  • 空值验证:通过strip()去除输入前后空格后,判断字符串是否为空,为空则调用sg.popup_error弹出提示。
  • 类型验证:使用try-except捕获ValueError,判断输入是否能转换为目标数值类型(如float),转换失败则弹出类型错误提示。
  • 单位按钮统一处理:将两个单位按钮的事件放在同一个判断分支中,复用空值验证逻辑,减少代码冗余。

内容的提问来源于stack exchange,提问作者Chinnu Sundaram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 16:34:57