【Python】利用 Tkinter 库写一个登录窗口

嗟!来食!(本文代码遵循 WTFPL 开源)

import tkinter as tk
import tkinter.messagebox as msgbox

ACCOUNT = 'admin'
PASSWORD = 'password'  # 此处建议搭配 MD5 使用,此处仅作演示
signed = False  # 控制变量法,设置登录状态,默认为未登录

def login():
    def judge(event: None):  # event 是 Tk().bind 需要传入的参数,尽管不需要用到,但是还是得加上
        if acc.get() != ACCOUNT or pwd.get() != PASSWORD:
            msgbox.showerror('*_*', '账号或密码错误,请重新输入')
        else:
            msgbox.showinfo('^_^', '管理员账号登录成功')
            global signed
            signed = True
            login_w.destroy()

    login_w = tk.Tk()  # 创建登录窗口
    login_w.title('Login')
    login_w.geometry('300x150')
    # 控制窗口监听键盘,如果按下回车键则触发和“登录”键一样的效果
    login_w.bind('<Key-Return>', judge)

    # 创建说明标签
    acc_label = tk.Label(login_w, width=7, text='用户名', compound='center')
    acc_label.place(x=30, y=20)
    pwd_label = tk.Label(login_w, width=7, text='密码', compound='center')
    pwd_label.place(x=30, y=60)

    # 创建输入框
    user_name = tk.StringVar()
    password = tk.StringVar()
    acc = tk.Entry(login_w, textvariable=user_name)
    acc.pack()
    acc.place(x=100, y=20)
    pwd = tk.Entry(login_w, show="*", textvariable=password)
    pwd.pack()
    pwd.place(x=100, y=60)

    # 创建“登录”按钮
    btn = tk.Button(login_w, text='登录', fg="black", width=7,
                    compound='center', bg="white", command=judge)
    btn.pack()
    btn.place(x=120, y=100)
    # 弹出窗口
    login_w.mainloop()

if __name__ == '__main__':
    login()

效果:

阅读剩余
THE END