在使用前,请确保你已经安装了tkinter和pymysql模块,并且替换了数据库连接的相关信息(localhost, your_username, your_password, your_db,charset),同时你需要有一个包含用户信息的表userinfo,其中应包含Name和PassWord字段。
准备好以上的相关信息后,接下来导入tkinter 和 pymysql 模块
import tkinter as tk
import pymysql
然后调用tkinter模块制作一个简易的登录界面
root = tk.Tk()
root.title("登录界面")
root.geometry('400x400')
label_username = tk.Label(root, text="用户名:")
label_username.place(x=100,y=80)
entry_username = tk.Entry(root)
entry_username.place(x=160,y=80)
label_password = tk.Label(root, text="密码:")
label_password.place(x=100,y=150)
entry_password = tk.Entry(root, show='*') # 密码字段用'*'显示
entry_password.place(x=160, y=150)
button_login = tk.Button(root, text="登录", command=login)
button_login.place(x=120,y=230)
button_cancle = tk.Button(root,text='取消',command=root.destroy)
button_cancle.place(x=220,y=230)
root.mainloop()
在用户点击登录按键的时候连接数据库查询并返回结果
button_login = tk.Button(root, text="登录", command=login)
button_login.place(x=120,y=230
下面是用户点击登录按键触发的方法
def login():
username = entry_username.get()
password = entry_password.get()
# 连接数据库
conn = pymysql.connect(
host='localhost', user='root', password='root123', db='test',charset='utf8')
cursor = conn.cursor()
# 执行SQL查询
sql_query = "SELECT * FROM userinfo WHERE Name = %s AND PassWord = %s"
cursor.execute(sql_query, (username, password))
# 检查是否有记录返回
if cursor.rowcount > 0:
print("登录成功")
# 这里可以执行登录成功后的操作
else:
print("登录失败:用户名或密码错误")
# 关闭数据库连接
cursor.close()
conn.close()
最后是取消按钮,当用户点击时执行 command = root.destroy,注销登录界面
button_cancle = tk.Button(root,text='取消',width=10,command=root.destroy)
button_cancle.place(x=220,y=230)
下面是完整代码:
# -*- encoding: utf-8 -*-
__Autor__ = 'Ocpt'
import tkinter as tk
import pymysql
def login():
username = entry_username.get()
password = entry_password.get()
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='root123', db='test',charset='utf8')
cursor = conn.cursor()
# 执行SQL查询
sql_query = "SELECT * FROM userinfo WHERE Name = %s AND PassWord = %s"
cursor.execute(sql_query, (username, password))
# 检查是否有记录返回
if cursor.rowcount > 0:
print("登录成功")
# 这里可以执行登录成功后的操作
else:
print("登录失败:用户名或密码错误")
# 关闭数据库连接
cursor.close()
conn.close()
root = tk.Tk()
root.title("登录界面")
root.geometry('400x400')
label_username = tk.Label(root, text="用户名:")
label_username.place(x=100,y=80)
entry_username = tk.Entry(root)
entry_username.place(x=160,y=80)
label_password = tk.Label(root, text="密码:")
label_password.place(x=100,y=150)
entry_password = tk.Entry(root, show='*') # 密码字段用'*'显示
entry_password.place(x=160, y=150)
button_login = tk.Button(root, text="登录",width=10, command=login)
button_login.place(x=120,y=230)
button_cancle = tk.Button(root,text='取消',width=10,command=root.destroy)
button_cancle.place(x=220,y=230)
root.mainloop()
这个示例代码提供了一个简单的登录界面,用户输入用户名和密码后点击登录按钮,程序会连接到数据库检查凭据,如果匹配则允许登录,否则提示错误。在实际应用中,你可能需要加密密码以及考虑更复杂的安全措施。