乐趣区

关于python:Python-Tkinter简单实现注册登录连接本地MySQL数据库

– coding: utf-8 –

“””
@date: 2022/01/09 17:40
@author: Anker
@python:v3.10
“””
import tkinter as tk
import tkinter.messagebox
import pymysql

定义要执行的创立表的 SQL 语句

test_sql = “””

            CREATE TABLE IF NOT EXISTS user(
            id INT auto_increment PRIMARY KEY,
            name varchar(20) not null,
            password varchar(20) not null
            )ENGINE=innodb DEFAULT CHARSET=utf8;
       """

登录窗口

window = tk.Tk()
window.title(‘ 学生考试零碎 ’)
window.geometry(‘800×500’)

登录背景图片

canvas = tk.Canvas(window, height=1920, width=1080)
login_background = tk.PhotoImage(file=’./view.png’)
login_image = canvas.create_image(0, 0, anchor=’nw’, image=login_background)
canvas.pack(side=’top’)

用户名明码标签

tk.Label(window, text=’ 用户名:’, bg=’yellow’).place(x=300, y=200)
tk.Label(window, text=’ 密 码:’, bg=’yellow’).place(x=300, y=250)

用户名输入框

var_user_name = tk.StringVar()
entry_user_name = tk.Entry(window, textvariable=var_user_name)
entry_user_name.place(x=370, y=200)

明码输入框

var_user_pwd = tk.StringVar()
entry_user_pwd = tk.Entry(window, textvariable=var_user_pwd, show=’*’)
entry_user_pwd.place(x=370, y=250)

登录函数

def user_login():

# 输入框获取用户名明码
user_name = var_user_name.get()
user_password = var_user_pwd.get()
# 连贯 test_sql 数据库
conn = pymysql.connect(host="localhost", user="root", password="123456", database="test_sql", charset="utf8")
curs = conn.cursor()
# 执行 SQL 语句,创立 user 数据表
curs.execute(test_sql)
# 执行 SQL 语句,从 user 数据表中查问 name 和 password 字段值
curs.execute("SELECT name,password FROM user")
# 将数据库查问的后果保留在 result 中
result = curs.fetchall()
# fetchone() 函数它的返回值是单个的元组, 也就是一行记录, 如果没有后果, 那就会返回 null
# fetchall() 函数它的返回值是多个元组, 即返回多个行记录, 如果没有后果, 返回的是 ()
# assert result, "数据库无该用户信息"   # 增加断言,判断数据库有无该用户信息,没有就间接断言谬误
# 登录账号操作
name_list = [it[0] for it in result]    # 从数据库查问的 result 中遍历查问元组中第一个元素 name
# 判断用户名或明码不能为空
if not(user_name and user_password):
    tk.messagebox.showwarning(title='正告', message='用户名或明码不能为空')
# 判断用户名和明码是否匹配
elif user_name in name_list:
    if user_password == result[name_list.index(user_name)][1]:
        tk.messagebox.showinfo(title='欢迎您', message='登录胜利!\r\n 以后登录账号为:' + user_name)
        selection()
    else:
        tk.messagebox.showerror(title='谬误', message='明码输出谬误')
# 账号不在数据库中,则弹出是否注册的框
else:
    is_signup = tk.messagebox.askyesno(title='提醒', message='该账号不存在,是否当初注册?')
    if is_signup:
        user_register()

注册函数

def user_register():

# 确认注册函数
def register_confirm():
    # 获取输入框内的内容
    name = new_name.get()
    password = new_password.get()
    password_confirm = new_password_confirm.get()
    # 先在本地手动创立一个 test_sql 数据库,而后连贯该数据库
    conn = pymysql.connect(host="localhost", user="root", password="123456", database="test_sql", charset="utf8")
    curs = conn.cursor()
    # 注册账号操作
    try:
        # 执行 SQL 语句,创立 user 数据表
        curs.execute(test_sql)
        # 向 user 数据表中插入语句
        insert_sql = "INSERT INTO user(name, password) VALUES ('%s','%s')" % (name, password)
        # 读取 user 数据表中的 name 和 password 字段值
        read_sql = f'''select * from user where name ="{name}"and password ="{password}"'''
        user_data = curs.execute(read_sql)
        # 判断注册账号和明码
        if not (name and password):
            tk.messagebox.showwarning(title='正告', message='注册账号或明码不能为空')
        elif password != password_confirm:
            tk.messagebox.showwarning(title='正告', message='两次明码输出不统一,请从新输出')
        else:
            if user_data.real:
                tk.messagebox.showwarning(title='正告', message='该注册账号已存在')
            else:
                curs.execute(insert_sql)
                tk.messagebox.showinfo(title='祝贺您', message='注册胜利!\r\n 注册账号为:' + name)
                print("数据插入胜利")
        # 提交到数据库执行
        conn.commit()
        curs.close()
    except IOError:
        print("数据插入失败")
        conn.rollback()
    # 敞开数据库连贯
    conn.close()
    window_sign_up.destroy()
# 注册窗口
window_sign_up = tk.Toplevel(window)
window_sign_up.geometry('350x200')
window_sign_up.title('欢送注册')
# 注册账号及标签、输入框
new_name = tk.StringVar()
tk.Label(window_sign_up, bg='green', text='注册账号:').place(x=50, y=10)
tk.Entry(window_sign_up, textvariable=new_name).place(x=150, y=10)
# 注册明码及标签、输入框
new_password = tk.StringVar()
tk.Label(window_sign_up, bg='green', text='密      码:').place(x=50, y=50)
tk.Entry(window_sign_up, textvariable=new_password, show='*').place(x=150, y=50)
# 反复明码及标签、输入框
new_password_confirm = tk.StringVar()
tk.Label(window_sign_up, bg='green', text='确认明码:').place(x=50, y=90)
tk.Entry(window_sign_up, textvariable=new_password_confirm, show='*').place(x=150, y=90)
# 确认注册按钮及地位
bt_confirm_sign_up = tk.Button(window_sign_up, bg='green', text='确认注册', command=register_confirm)
bt_confirm_sign_up.place(x=150, y=130)

选择题函数

def selection():

def wrong():
    tk.messagebox.showerror(title='谬误', message='道歉,您答错了')
def right():
    tk.messagebox.showinfo(title='提醒', message='祝贺您,答对了')
# 选择题窗口
window_options = tk.Toplevel(window)
window_options.geometry('350x200')
window_options.title('选择题')
# 在图形界面上创立一个标签 label 用以显示并搁置
var = tk.StringVar()  # 定义一个 var 用来将 radiobutton 的值和 Label 的值分割在一起.
lab = tk.Label(window_options, bg='red', fg='white', width=50)
lab.pack()
lab.config(text='第 1 题:两个锐角均为 60 度的三角形是什么三角形()' + var.get())
# 创立 3 个 radiobutton 选项,[黄金](https://www.gendan5.com/nmetal/gold.html) 其中 variable=var, value='A' 示意:当鼠标选中其中一个选项,把 value 的值 A 放到变量 var 中,而后赋值给 variable
radio1 = tk.Radiobutton(window_options, text='A:锐角三角形', variable=var, value='A', command=wrong)
radio1.pack()
radio2 = tk.Radiobutton(window_options, text='B:钝角三角形', variable=var, value='B', command=wrong)
radio2.pack()
radio3 = tk.Radiobutton(window_options, text='C:等边三角形', variable=var, value='C', command=right)
radio3.pack()
radio4 = tk.Radiobutton(window_options, text='D:直角三角形', variable=var, value='D', command=wrong)
radio4.pack()

注册和登录按钮

bt_register = tk.Button(window, bg=’yellow’, text=’ 注册 ’, command=user_register)
bt_register.place(x=380, y=300)
bt_login = tk.Button(window, bg=’yellow’, text=’ 登录 ’, command=user_login)
bt_login.place(x=440, y=300)

主循环

window.mainloop()

退出移动版