pyqt学生信息管理系统
时间: 2023-12-18 09:03:58 浏览: 85
以下是一个简单的PyQt学生信息管理系统的示例,包括添加、删除、修改和查询学生信息的功能:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
class StudentInfo(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('学生信息管理系统')
self.resize(500, 400)
# 创建表格
self.tableWidget = QtWidgets.QTableWidget(self)
self.tableWidget.setGeometry(QtCore.QRect(10, 10, 480, 300))
self.tableWidget.setColumnCount(3)
self.tableWidget.setHorizontalHeaderLabels(['学号', '姓名', '年龄'])
# 创建按钮
self.addButton = QtWidgets.QPushButton('添加', self)
self.addButton.setGeometry(QtCore.QRect(50, 330, 80, 30))
self.delButton = QtWidgets.QPushButton('删除', self)
self.delButton.setGeometry(QtCore.QRect(150, 330, 80, 30))
self.modifyButton = QtWidgets.QPushButton('修改', self)
self.modifyButton.setGeometry(QtCore.QRect(250, 330, 80, 30))
self.queryButton = QtWidgets.QPushButton('查询', self)
self.queryButton.setGeometry(QtCore.QRect(350, 330, 80, 30))
# 绑定按钮事件
self.addButton.clicked.connect(self.addStudent)
self.delButton.clicked.connect(self.delStudent)
self.modifyButton.clicked.connect(self.modifyStudent)
self.queryButton.clicked.connect(self.queryStudent)
# 初始化数据库
self.db = QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName('student.db')
self.db.open()
# 添加学生信息
def addStudent(self):
query = QSqlQuery()
id = self.tableWidget.rowCount() + 1
name = '张三'
age = 18
query.exec(f"INSERT INTO student VALUES ({id}, '{name}', {age})")
self.queryStudent()
# 删除学生信息
def delStudent(self):
row = self.tableWidget.currentRow()
id = self.tableWidget.item(row, 0).text()
query = QSqlQuery()
query.exec(f"DELETE FROM student WHERE id={id}")
self.queryStudent()
# 修改学生信息
def modifyStudent(self):
row = self.tableWidget.currentRow()
id = self.tableWidget.item(row, 0).text()
name = '李四'
age = 20
query = QSqlQuery()
query.exec(f"UPDATE student SET name='{name}', age={age} WHERE id={id}")
self.queryStudent()
# 查询学生信息
def queryStudent(self):
query = QSqlQuery()
query.exec("SELECT * FROM student")
self.tableWidget.setRowCount(0)
while query.next():
row = self.tableWidget.rowCount()
self.tableWidget.insertRow(row)
for i in range(3):
item = QTableWidgetItem(str(query.value(i)))
self.tableWidget.setItem(row, i, item)
if __name__ == '__main__':
app = QApplication([])
window = StudentInfo()
window.show()
app.exec_()
```
阅读全文