用pyqt5写一个职工管理界面 用pymysql连接这个界面
时间: 2024-05-15 21:16:07 浏览: 109
python实现好看的GUI界面pyqt5
5星 · 资源好评率100%
我们可以使用PyQt5来创建一个简单的职工管理界面,使用pymysql来连接数据库并执行相关操作。以下是一个示例代码:
```python
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', password='password', database='employees')
cursor = db.cursor()
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Employee Management System'
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(100, 100, 800, 500)
# 添加职工信息
self.add_employee_lbl = QLabel('Add Employee', self)
self.add_employee_lbl.move(50, 50)
self.name_lbl = QLabel('Name:', self)
self.name_lbl.move(50, 100)
self.name_input = QLineEdit(self)
self.name_input.move(150, 100)
self.age_lbl = QLabel('Age:', self)
self.age_lbl.move(50, 150)
self.age_input = QLineEdit(self)
self.age_input.move(150, 150)
self.salary_lbl = QLabel('Salary:', self)
self.salary_lbl.move(50, 200)
self.salary_input = QLineEdit(self)
self.salary_input.move(150, 200)
self.add_employee_btn = QPushButton('Add Employee', self)
self.add_employee_btn.move(150, 250)
self.add_employee_btn.clicked.connect(self.add_employee)
# 显示职工信息
self.show_employee_lbl = QLabel('Show Employee', self)
self.show_employee_lbl.move(400, 50)
self.employee_table = QTableWidget(self)
self.employee_table.move(400, 100)
self.employee_table.resize(350, 300)
self.employee_table.setColumnCount(4)
self.employee_table.setHorizontalHeaderLabels(['ID', 'Name', 'Age', 'Salary'])
self.show_employee_btn = QPushButton('Show Employee', self)
self.show_employee_btn.move(600, 415)
self.show_employee_btn.clicked.connect(self.show_employee)
self.show()
def add_employee(self):
name = self.name_input.text()
age = self.age_input.text()
salary = self.salary_input.text()
# 将职工信息插入数据库
sql = f"INSERT INTO employees(name, age, salary) VALUES ('{name}', {age}, {salary})"
cursor.execute(sql)
db.commit()
self.name_input.setText('')
self.age_input.setText('')
self.salary_input.setText('')
def show_employee(self):
# 查询所有职工信息
sql = "SELECT * FROM employees"
cursor.execute(sql)
results = cursor.fetchall()
self.employee_table.setRowCount(0)
for row_number, row_data in enumerate(results):
self.employee_table.insertRow(row_number)
for column_number, data in enumerate(row_data):
self.employee_table.setItem(row_number, column_number, QTableWidgetItem(str(data)))
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
```
在这个示例代码中,我们创建了一个简单的职工管理界面,包括添加职工信息和显示职工信息两个功能。我们使用PyQt5创建了界面,使用pymysql连接数据库并执行相关操作,包括插入职工信息和查询所有职工信息。我们还使用了QTableWidget来显示职工信息。您需要根据您的实际情况修改代码中的数据库连接信息。
阅读全文