Python中利用Tkinter和SQLite制作登录和注册界面(第14节)


在Python中,Tkinter库是最常用于构建GUI应用程序的标准GUI库。Tkinter库使用起来比较简单,容易上手。在本节教程中,我们将使用Tkinter库结合SQLite数据库来创建登录和注册界面。SQLite数据库是Python中一个轻量级的嵌入式关系型数据库管理系统,不需要单独的服务器进程,数据库直接存储在单一文件中,无需安装和配置,在Python中可以直接使用。

1、利用Tkinter和SQLite制作用户登录和注册界面程序介绍

我们的目标是开发一个登录和注册界面程序,使用Tkinter库来设计登录和注册界面布局,并结合SQLite数据库来存储用户信息。该程序运行后,会在当前工作目录下创建一个名为“login.db”数据库文件,并在数据库中创建一个user数据库表,用于保存用户名和密码。user数据库表中包含两个字段:“username”(用户名,不可为空)、“password”(密码,不可为空)。

在登录界面中,用户可以尝试登录,如果出现三次失败,则会自动终止程序。在注册界面中,允许用户输入新的账号和密码,如果注册信息验证成功,信息将会被保存到“login.db”数据库文件中。

2、利用Tkinter和SQLite制作用户登录和注册界面程序演示

Python中利用Tkinter和SQLite制作登录和注册界面

Python中利用Tkinter和SQLite制作登录和注册界面

3、代码实现

(1)导入必要的库

import tkinter as tk
from tkinter import messagebox
import os, sys, sqlite3

这里导入了tkinter库用于创建GUI应用图形界面,tkinter的messagebox用于消息提示。os库用于文件和文件夹操作。sys库可以与Python解释器及其运行环境进行交互。sqlite3库用于连接SQLite数据库,保存和查找用户信息。

(2)连接到数据库

import os, sys, sqlite3

# 定义“login.db”数据库文件,用于保存注册数据
name_file = 'login.db'

# 连接到数据库(如果数据库不存在,则会自动创建)
try:
    if not os.path.exists(name_file):
        # 创建表格(如果尚不存在)
        def get_db_connection():
            conn = sqlite3.connect(name_file)
            return conn

        # 插入数据
        def create_db():
            conn = get_db_connection()
            c = conn.cursor()
            c.execute('''CREATE TABLE IF NOT EXISTS user (
                            username char not null,
                            password char not null)''')

            # 提交事务并关闭连接
            conn.commit()  # 提交事务以保存更改
            conn.close()   # 关闭连接
        create_db()
except:
    pass

这里SQLite数据库文件名为“login.db”,我们先判断数据库文件是否存在,如果数据库文件不存在,则会自动创建该数据库文件。

(3)利用Tkinter和SQLite制作用户登录和注册界面程序,完整代码如下所示:

动手练一练:

import tkinter as tk
from tkinter import messagebox
import os, sys, sqlite3

# 获取当前脚本文件所在的目录
default_directory = os.path.dirname(os.path.abspath(__file__))
# 将当前脚本文件所在的目录设置为工作目录
os.chdir(default_directory)

# 定义“login.db”数据库文件,用于保存注册数据
name_file = 'login.db'

# 连接到数据库(如果数据库不存在,则会自动创建)
try:
    if not os.path.exists(name_file):
        # 创建表格(如果尚不存在)
        def get_db_connection():
            conn = sqlite3.connect(name_file)
            return conn

        # 插入数据
        def create_db():
            conn = get_db_connection()
            c = conn.cursor()
            c.execute('''CREATE TABLE IF NOT EXISTS user (
                            username char not null,
                            password char not null)''')

            # 提交事务并关闭连接
            conn.commit()  # 提交事务以保存更改
            conn.close()   # 关闭连接
        create_db()
except:
    pass

# 定义函数,在数据库中匹配用户名和密码是否正确
def login(username, password):
    connection = sqlite3.connect(name_file)
    sql = 'SELECT * FROM user WHERE username=? and password=?'
    cursor = connection.cursor()
    cursor.execute(sql, (username, password))
    result = cursor.fetchall()
    connection.commit()
    connection.close()
    if len(result) == 0:
        return False
    else:
        return True

# 定义登录验证函数
def login_verify(username, password):
    errMessage = ""
    result = False
    if len(username) == 0:
        errMessage = errMessage + "用户名不能为空!"
    elif len(password) == 0:
        errMessage = errMessage + "密码不能为空!"
    else:
        result = login(username, password)
    if result == True:
        errMessage = errMessage + "登录成功"
    else:
        errMessage = errMessage + "用户名或密码错误"
    return errMessage

# 定义函数,向数据库中添加用户名和密码
def add(username, password):
    connection = sqlite3.connect(name_file)
    sql = '''INSERT INTO user (username, password) VALUES (?,?)'''
    cursor = connection.cursor()
    cursor.execute(sql, (username, password,))
    result = cursor.fetchall()
    connection.commit()
    connection.close()
    if len(result) == 0:
        return True
    else:
        return False

# 定义一个Tkinter类
class Tkinter(object):
    # 初始化
    def __init__(self):
        self.windows = tk.Tk()
        self.count = 3

    # 定义函数,用于绑定“登录”按钮
    def make_login(self):
        errMessage = ""
        # 获取用户输入的信息
        user_name = self.user_name_entry.get()
        user_password = self.user_password_entry.get()

        new_errMessage = login_verify(user_name, user_password)
        errMessage = errMessage + new_errMessage

        # 判断用户输入错误的次数,大于3次就结束程序
        if self.count == 0:
            messagebox.showinfo('警告!', '非法入侵!\n启动自动销毁模式!!!')
            self.windows.quit()
            sys.exit(0)

        # 判断是否登录成功
        if errMessage != '登录成功':
            messagebox.showinfo('提示', errMessage +',你还可以登录%s次' % self.count)
            self.count -= 1
        else:
            new_errMessage == '登录成功'
            messagebox.showinfo(title='welcome', message='欢迎您:' + user_name)

    # 定义函数,用于绑定“返回”按钮
    def come_back(self):
        # 销毁掉注册窗口
        self.register_window.destroy()

    # 定义函数,用于注册功能
    def register(self):
        # 获取用户输入的数据
        username = self.var_user_name.get()
        password1 = self.var_user_password.get()
        password2 = self.var_user_repassword.get()

        # 连接到数据库  
        connection = sqlite3.connect(name_file)
        cursor = connection.cursor()

        # 执行查询操作
        cursor.execute("SELECT username FROM user WHERE username = ?", (username,))
        # 使用fetchone()获取单个结果
        result = cursor.fetchone()
        # 检查用户名是否存在、密码是否为空、两次密码输入是否一致
        if username and result:
            messagebox.showerror('错误','该用户名已存在,请填写其它用户名')
        elif password1 =='' or username=='':
            messagebox.showerror('失败!','用户名或密码不能为空')
        elif password1 !=password2:
            messagebox.showerror('失败!', '注册失败,两次输入的密码不一致!')
        # 如果注册信息正常,则将用户名和密码写入数据库
        else:
            add(username,password1)
            messagebox.showinfo('欢迎','注册成功')
            # 如果注册成功,则关闭注册框
            self.register_window.destroy()

        # 关闭Cursor和Connection
        cursor.close()
        connection.close()

    # 定义函数,用于绑定“注册”按钮
    def register_button(self):
        # 定义注册窗口
        self.register_window = tk.Tk()
        # 设置注册窗口居中
        window_height = 330
        window_width = 230
        screen_width = self.register_window.winfo_screenwidth()
        screen_height = self.register_window.winfo_screenheight()
        x = (screen_width - window_height) / 2
        y = (screen_height - window_width) / 2
        self.register_window.geometry('%dx%d+%d+%d' % (window_height, window_width, x, y))
        self.register_window.title('用户注册界面')
        self.register_window.resizable(width=False, height=False)

        # 创建用户名和密码标签
        tk.Label(self.register_window, text="用户名:", font=('宋体', 15), width=10).place(x=30, y=20)
        tk.Label(self.register_window, text="密码:", font=('宋体', 15), width=10).place(x=30, y=70)
        tk.Label(self.register_window, text="确认密码:", font=('宋体', 15), width=10).place(x=30, y=120)

        # 创建用户名输入框
        self.var_user_name = tk.Entry(self.register_window)
        self.var_user_name.place(x=140, y=25)
        # 创建密码输入框
        self.var_user_password = tk.Entry(self.register_window, show="*")
        self.var_user_password.place(x=140, y=75)
        # 创建再次确认密码输入框
        self.var_user_repassword = tk.Entry(self.register_window, show="*")
        self.var_user_repassword.place(x=140, y=125)

        # 创建“注册”和“返回”按钮
        register_button1 = tk.Button(self.register_window, text="注册", font=('宋体', 15), width=10, command=self.register)
        register_button1.place(x=100, y=170)
        return_button = tk.Button(self.register_window, text="返回", font=('宋体', 10), width=5, command=self.come_back)
        return_button.place(x=250, y=180)

        # 运行注册窗口
        self.register_window.mainloop()

    # 定义函数,创建登录主窗口
    def main(self):
        # 设置登录主窗口居中
        window_height = 330
        window_width = 230
        screen_width = self.windows.winfo_screenwidth()
        screen_height = self.windows.winfo_screenheight()
        x = (screen_width - window_height) / 2
        y = (screen_height - window_width) / 2
        self.windows.geometry('%dx%d+%d+%d' % (window_height, window_width, x, y))
        self.windows.title('用户登录界面')
        self.windows.resizable(width=False, height=False)

        # 创建用户名和密码标签
        tk.Label(self.windows, text="用户名:", font=('宋体', 15), width=10).place(x=30, y=40)
        tk.Label(self.windows, text="密码:", font=('宋体', 15), width=10).place(x=30, y=90)

        # 创建用户名输入框
        self.user_name_entry = tk.StringVar()
        self.username = tk.Entry(self.windows,textvariable=self.user_name_entry)
        self.username.place(x=140, y=45)
        # 创建密码输入框
        self.user_password_entry = tk.StringVar()
        self.password = tk.Entry(self.windows, textvariable=self.user_password_entry, show="*")
        self.password.place(x=140, y=95)

        # 创建“登录”和“注册”按钮
        button = tk.Button(self.windows, text="登录", font=('宋体', 15), width=10, command=self.make_login)
        button.place(x=40, y=150)
        button1 = tk.Button(self.windows, text="注册", font=('宋体', 15), width=10, command=self.register_button)
        button1.place(x=180, y=150)

        # 运行登录窗口
        self.windows.mainloop()

# 当前模块直接被执行
if __name__ == '__main__':
    app = Tkinter()
    app.main()