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

如何在Tkinter登录系统中实现用户未选择加密操作时自动提醒?

登录系统加密模式选择校验修复方案

存在的问题

  • 没有预先判断加密模式列表的选中状态,直接调用lis.curselection()取值会在用户未选择时抛出Tkinter异常
  • 原判断未选择的逻辑r not in r语法无效,永远无法触发对应提示
  • 未绑定回车键事件,按下回车无法触发校验逻辑
  • 校验逻辑顺序混乱,账号密码和加密模式的判断逻辑重复冗余

修复后完整代码

from tkinter import messagebox
from tkinter import *


window = Tk()

window.title('Login')
window.geometry('320x200')
window.resizable(True, True)

name = StringVar()
password = StringVar()

def crypt():
    # 优先判断是否选择加密模式
    select_index = lis.curselection()
    if not select_index:
        messagebox.showerror('错误', '请选择消息加密类型')
        return
    
    crypto_mode = lis.get(select_index)
    string_name = name.get().strip()
    string_password = password.get().strip()

    # 校验账号密码
    if string_name != 'John' or string_password != '6789':
        messagebox.showerror('错误', '账号或密码错误')
        return
    
    # 校验通过执行对应逻辑
    window.after(1000, lambda: window.destroy())
    if crypto_mode == 'Use encrypted':
        print('Hello.')
    else:
        print('Hello bro!')

entry = Entry(window, textvariable=name, width=10)
entry.grid(column=1, pady=7, padx=4)

label = Label(window, text='Enter name: ')
label.grid(row=0, padx=1)

entry1 = Entry(window, textvariable=password, width=10, show='*')
entry1.grid(column=1, pady=7, padx=2)

label1 = Label(window, text='Enter password: ')
label1.grid(row=1, padx=1)

r = ['Use encrypted']
c = ['Use decrypted']
lis = Listbox(window, selectmode=SINGLE, width=10, height=2)
lis.grid(column=1, row=2, pady=7, padx=2)
for i in r:
    lis.insert(END, i)
for i in c:
    lis.insert(END, i)

label_crypto = Label(window, text='Encrypted/decrypted message: ', bg='black', fg='red')
label_crypto.grid(row=2)

button = Button(window, text='Enter', command=crypt)
button.grid(pady=30)

# 绑定回车键触发校验
window.bind('<Return>', lambda event: crypt())

window.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:36:04