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

Tkinter登录界面输入指定密码点击Enter按钮无法关闭项目求助

问题定位

你的代码没有实际执行窗口关闭的逻辑,当密码匹配时执行的command=root.quit只是将root.quit方法对象赋值给了局部变量command,没有真正调用退出方法,所以窗口不会关闭。

修复方法

将if判断分支里的代码修改为直接调用关闭方法即可,tkinter有两种常用的关闭写法,选一种就行:

  • root.quit():终止tkinter主循环,直接退出程序
  • root.destroy():销毁根窗口对象,结束程序

修正后的完整代码

import tkinter as tk
from tkinter import *

root = Tk()
root.title("Login")
root.geometry("157x160")

def submit():
    name = name_var.get()
    password = passw_var.get()

    if password == "delete":
        print("Closed")
        # 替换原赋值语句,直接调用退出方法
        root.quit()
    else:
        print('User: ' + name)
        print('Password: ' + password)
        name_var.set("")
        passw_var.set("")

name_var = tk.StringVar()
passw_var = tk.StringVar()

name_label = tk.Label(root, text='User', font=('calibre', 10, 'bold'))
name_entry = tk.Entry(root, textvariable=name_var, font=('calibre', 10, 'normal'))
passw_label = tk.Label(root, text='Password', font=('calibre', 10, 'bold'))
passw_entry = tk.Entry(root, textvariable=passw_var, font=('calibre', 10, 'normal'), show="X")
sub_btn = tk.Button(root, text='Enter', command=submit)

name_label.place(x=10, y=10)
name_entry.place(x=13, y=25)
passw_label.place(x=10, y=60)
passw_entry.place(x=13, y=75)
sub_btn.place(x=48, y=120)

root.mainloop()

后续优化提示

之后要加用户名校验的话,直接修改if判断条件即可,示例:
if name == "你的预设用户名" and password == "delete":

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:48:03