pyqt5 mysql登录注册系统界面
时间: 2023-10-19 16:05:18 浏览: 48
以下是一个简单的PyQt5 MySQL登录注册系统界面的示例代码:
```python
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QHBoxLayout, QMessageBox
import mysql.connector
class Login(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Login")
self.username = QLineEdit()
self.password = QLineEdit()
self.password.setEchoMode(QLineEdit.Password)
login_button = QPushButton("Login")
login_button.clicked.connect(self.login)
register_button = QPushButton("Register")
register_button.clicked.connect(self.register)
layout = QVBoxLayout()
layout.addWidget(QLabel("Username:"))
layout.addWidget(self.username)
layout.addWidget(QLabel("Password:"))
layout.addWidget(self.password)
button_layout = QHBoxLayout()
button_layout.addWidget(login_button)
button_layout.addWidget(register_button)
layout.addLayout(button_layout)
self.setLayout(layout)
def login(self):
username = self.username.text()
password = self.password.text()
conn = mysql.connector.connect(user='root', password='password', host='localhost', database='database')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))
user = cursor.fetchone()
if user is not None:
QMessageBox.information(self, "Login", "Login successful")
else:
QMessageBox.warning(self, "Login", "Invalid username or password")
conn.close()
def register(self):
username = self.username.text()
password = self.password.text()
conn = mysql.connector.connect(user='root', password='password', host='localhost', database='database')
cursor = conn.cursor()
cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, password))
conn.commit()
QMessageBox.information(self, "Register", "Registration successful")
conn.close()
if __name__ == '__main__':
app = QApplication([])
login = Login()
login.show()
app.exec_()
```
在这个示例中,我们创建了一个登录窗口,并在该窗口上添加了用户名和密码的 QLineEdit,以及一个登录和注册按钮。当用户点击登录或注册按钮时,我们将从数据库中检索或插入相应的用户记录。我们使用了 PyMySQL 模块来连接 MySQL 数据库。注意,在实际应用程序中,你需要使用加密技术来保护用户密码,以免密码被未经授权的用户访问。