GUI项目实战:用tkinter+sqlite3制作可登录可注册的GUI界面
import tkinter as tk
import sqlite3
# 连接数据库(如果不存在则创建)
conn = sqlite3.connect('userinfo.db')
cur = conn.cursor()
# 创建用户表
cur.execute('''CREATE TABLE IF NOT EXISTS user_table(
username TEXT PRIMARY KEY NOT NULL,
password TEXT NOT NULL);''')
conn.commit()
def register():
reg_username = username_reg.get()
reg_password = password_reg.get()
cur.execute("INSERT INTO user_table(username, password) VALUES (?, ?)", (reg_username, reg_password))
conn.commit()
conn.close()
print("Registration successful!")
def login():
log_username = username_log.get()
log_password = password_log.get()
cur.execute("SELECT * FROM user_table WHERE username=? AND password=?", (log_username, log_password))
if cur.fetchone() is not None:
print("Login successful!")
else:
print("Login failed! Username and/or password incorrect.")
# 创建主窗口
root = tk.Tk()
root.title("Login/Register System")
# 创建登录窗口
login_frame = tk.Frame(root)
login_frame.pack(side=tk.TOP)
tk.Label(login_frame, text="Username:").pack(side=tk.LEFT)
username_log = tk.Entry(login_frame)
username_log.pack(side=tk.LEFT)
tk.Label(login_frame, text="Password:").pack(side=tk.LEFT)
password_log = tk.Entry(login_frame, show='*')
password_log.pack(side=tk.LEFT)
login_button = tk.Button(login_frame, text="Login", command=login)
login_button.pack(side=tk.LEFT)
# 创建注册窗口
register_frame = tk.Frame(root)
register_frame.pack(side=tk.TOP)
tk.Label(register_frame, text="Username:").pack(side=tk.LEFT)
username_reg = tk.Entry(register_frame)
username_reg.pack(side=tk.LEFT)
tk.Label(register_frame, text="Password:").pack(side=tk.LEFT)
password_reg = tk.Entry(register_frame, show='*')
password_reg.pack(side=tk.LEFT)
register_button = tk.Button(register_frame, text="Register", command=register)
register_button.pack(side=tk.LEFT)
root.mainloop()
这段代码使用了tkinter库来创建GUI界面,并结合sqlite3来管理用户数据。用户可以通过注册窗口输入用户名和密码来注册账号,输入的信息会被保存到名为userinfo.db
的SQLite数据库中。登录窗口允许用户使用他们的用户名和密码来尝试登录。如果用户名和密码正确,会打印出登录成功的消息,否则会打印登录失败的消息。这个简单的例子展示了如何使用数据库来管理用户认证信息,并在GUI中处理用户的登录和注册请求。
评论已关闭