tk+mysql实现注册登录,登录和注册的输入框都不能为空(详细完整的代码)
时间: 2023-06-14 10:08:18 浏览: 46
以下是使用Tkinter和MySQL实现注册和登录功能的完整代码:
```python
from tkinter import *
import mysql.connector
# 创建MySQL连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 创建数据库表
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255), password VARCHAR(255))")
# 注册函数
def register():
# 获取输入框中的值
username = username_entry.get()
password = password_entry.get()
# 如果输入框为空,则弹出错误提示框
if username == "" or password == "":
error_label.config(text="请填写用户名和密码", fg="red")
return
# 查询数据库中是否已存在该用户
mycursor.execute("SELECT * FROM users WHERE username = %s", (username,))
result = mycursor.fetchone()
# 如果已存在该用户,则弹出错误提示框
if result:
error_label.config(text="该用户名已被注册", fg="red")
return
# 向数据库中插入新用户
mycursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
mydb.commit()
# 显示成功提示框
error_label.config(text="注册成功", fg="green")
# 登录函数
def login():
# 获取输入框中的值
username = username_entry.get()
password = password_entry.get()
# 如果输入框为空,则弹出错误提示框
if username == "" or password == "":
error_label.config(text="请填写用户名和密码", fg="red")
return
# 查询数据库中是否存在该用户
mycursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))
result = mycursor.fetchone()
# 如果不存在该用户,则弹出错误提示框
if not result:
error_label.config(text="用户名或密码错误", fg="red")
return
# 显示成功提示框
error_label.config(text="登录成功", fg="green")
# 创建窗口和组件
root = Tk()
root.title("登录/注册")
username_label = Label(root, text="用户名")
username_label.pack()
username_entry = Entry(root)
username_entry.pack()
password_label = Label(root, text="密码")
password_label.pack()
password_entry = Entry(root, show="*")
password_entry.pack()
register_button = Button(root, text="注册", command=register)
register_button.pack()
login_button = Button(root, text="登录", command=login)
login_button.pack()
error_label = Label(root, text="")
error_label.pack()
root.mainloop()
```
请注意,您需要将 `yourusername` 和 `yourpassword` 替换为您的MySQL用户名和密码,并且需要在MySQL中创建一个名为 `mydatabase` 的新数据库。此外,如果您想要在注册时添加其他字段,例如电子邮件地址或年龄,您需要修改数据库表的结构并相应地修改代码。