PyQt 是一个用于创建桌面应用程序的 Python 绑定库,它基于 Qt 框架。MySQL 是一个流行的关系型数据库管理系统。结合 PyQt 和 MySQL,可以创建具有数据库交互功能的图形用户界面(GUI)应用程序。
以下是一个简单的 PyQt MySQL 登录界面的示例代码:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QVBoxLayout, QMessageBox
import mysql.connector
class LoginWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('Login')
self.setGeometry(100, 100, 300, 200)
layout = QVBoxLayout()
self.label_username = QLabel('Username:', self)
self.text_username = QLineEdit(self)
layout.addWidget(self.label_username)
layout.addWidget(self.text_username)
self.label_password = QLabel('Password:', self)
self.text_password = QLineEdit(self)
self.text_password.setEchoMode(QLineEdit.Password)
layout.addWidget(self.label_password)
layout.addWidget(self.text_password)
self.button_login = QPushButton('Login', self)
self.button_login.clicked.connect(self.login)
layout.addWidget(self.button_login)
self.setLayout(layout)
def login(self):
username = self.text_username.text()
password = self.text_password.text()
try:
conn = mysql.connector.connect(user='your_username', password='your_password', host='localhost', database='your_database')
cursor = conn.cursor()
query = "SELECT * FROM users WHERE username = %s AND password = %s"
cursor.execute(query, (username, password))
result = cursor.fetchone()
if result:
QMessageBox.information(self, 'Success', 'Login successful!')
# 这里可以跳转到主界面或其他模块
else:
QMessageBox.warning(self, 'Error', 'Invalid username or password.')
except mysql.connector.Error as err:
QMessageBox.critical(self, 'Error', f'Database error: {err}')
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = LoginWindow()
window.show()
sys.exit(app.exec_())通过以上步骤和示例代码,你可以创建一个基本的 PyQt MySQL 登录界面,并解决常见的技术问题。
没有搜到相关的文章