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

Python Tkinter条件判断失效求助:登录验证始终执行else分支

Tkinter登录验证密码判断失败的解决方法

核心问题

你直接将Entry组件对象和字符串"python"做比较,而不是获取输入框内的文本内容。password_input是Tkinter的Entry实例,并非用户输入的字符串,所以password_input == "python"永远返回False,导致逻辑始终走else分支。

解决步骤

  1. 获取输入框文本:在click_check_button函数中,使用password_input.get()方法提取用户输入的密码字符串,再与目标密码对比。
  2. 优化组件重复创建问题:原代码每次点击按钮都会新建Label,导致界面元素叠加。建议提前创建一个结果标签,点击时仅更新它的文本和样式。

修正后的完整代码

from tkinter import *

ROOT = Tk()
ROOT.geometry("500x300+50+50")
ROOT.config(bg="grey")
ROOT.title("登录窗口")

user_tag = Label(text="用户名: ")
user_tag.grid(row=0, column=0)
user_tag.config(bg="grey", font=("Arial", 16))

password_tag = Label(text="密码: ")
password_tag.grid(row=1, column=0)
password_tag.config(bg="grey", font=("Arial", 16))

user_input = Entry()
user_input.grid(row=0, column=1)
user_input.config(bg="red", font=("Comic Sans", 16))
user_input.insert(0, "请输入用户名...")

password_input = Entry()
password_input.grid(row=1, column=1)
password_input.config(bg="red", font=("Comic Sans", 16), show="*")
password_input.insert(0, "***********")

# 提前创建结果标签,初始为空
result_label = Label(bg="grey")
result_label.grid(row=4, column=1)

space_0 = Label(text=" ", bg="grey")
space_0.grid(row=3)

space_1 = Label(text=" ", bg="grey")
space_1.grid(row=4, column=0)

space_2 = Label(text=" ", bg="grey")
space_2.grid(row=2, column=0)

def click_check_button():
    # 获取输入的密码字符串
    input_password = password_input.get()
    if input_password == "python":
        result_label.config(text="¡Acceso concedido!", bg="green", font=("Arial", 22))
    else:
        result_label.config(text="¡Acceso denegado!", bg="red", font=("Arial", 22))

check_button = Button(text="登录", font=("Arial", 20))
check_button.grid(row=2, column=1)
check_button.config(bg="yellow", activebackground="orange", command=click_check_button)

ROOT.mainloop()

额外优化提示

可以给输入框绑定点击事件,自动清空初始提示文本,提升交互体验:

def clear_user_input(event):
    if user_input.get() == "请输入用户名...":
        user_input.delete(0, END)

def clear_password_input(event):
    if password_input.get() == "***********":
        password_input.delete(0, END)

user_input.bind("<Button-1>", clear_user_input)
password_input.bind("<Button-1>", clear_password_input)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:29:59