You need to enable JavaScript to run this app. 基于guizero开发用户名密码校验功能,提交后始终提示认证失败如何修复?
优惠活动
大模型
产品
解决方案
定价
更多

基于guizero开发用户名密码校验功能,提交后始终提示认证失败如何修复?

问题根因

你遇到的无论输入正确账号密码都弹出错误提示的核心原因,是校验逻辑没有正确读取输入框的实际内容:

  • guizero 中的 input_box1、input_box2 都是TextBox类的组件实例,本身不是字符串类型,直接拿组件对象和固定值"a"、"b"做相等比较,结果永远为假,所以校验分支永远走错误提示的逻辑
  • 要获取用户在输入框里实际敲入的文本,必须访问组件的.value属性。
具体修复点
  • 调整校验判断条件,改为读取两个输入框的.value属性值和预设匹配项做对比,同时可以加.strip()方法过滤用户不小心输入的前后空格,避免不必要的匹配失败
  • 因为后续要修改全局预留的passed变量,需要在authenticate函数开头声明该变量为全局引用,否则函数内部赋值的passed=True是临时局部变量,不会同步更新到全局的预留状态
  • 可以优化按钮显示逻辑:目前你把写着"Submit"的Text组件和PushButton放在同一个网格位置叠加显示,完全可以直接给PushButton设置text="Submit"参数作为按钮自带的文字,避免组件叠加造成的显示错位
修复后可运行代码
from guizero import App, Text, TextBox, PushButton, info, Picture

passed = False

def authenticate():
    # 声明全局变量引用,否则无法修改全局预留的passed值
    global passed
    # 读取输入框实际值,去除前后空格后做匹配
    if input_box1.value.strip() == "a" and input_box2.value.strip() == "b":
        passed = True
        info("Welcome", "Level 5 identification accepted. Welcome, Dr. Artyom.")
    else:
        info("Password", "Your username or password is incorrect.")


app = App(title="AppTest", width=900, height=600, layout="grid", bg=[255,255,255])

text = Text(app, text=" ", grid=[0,0])
text = Text(app, text="                                  ", grid=[1,1])
text = Text(app, text="Please enter a valid username and password.", grid=[2,1], color=[0,0,0])
text = Text(app, text="             ", grid=[2,2])

input_box1 = TextBox(app, grid=[2,3], height=1, width=25)
text = Text(app, text="Username", grid=[1,3], color=[0,0,0])
text = Text(app, text="             ", grid=[2,4])

input_box2 = TextBox(app, grid=[2,5], hide_text=True, height=1, width=25)
text = Text(app, text="Password", grid=[1,5], color=[0,0,0])
text = Text(app, text="        ", grid=[2,6])

# 直接在PushButton上设置显示文字,删除原有叠加的Text组件
submit = PushButton(app, enabled=True, command=authenticate, height=1, width=6, grid=[2,7], text="Submit")

text = Text(app, text="          ", grid = [3,11])
picture = Picture(app, image="D:\python files\logtext.gif", grid=[2,12])

app.display()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 06:36:08