侧边栏壁纸
  • 累计撰写 29 篇文章
  • 累计创建 10 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

pyqt5

十点差三分
2025-05-18 / 0 评论 / 0 点赞 / 5 阅读 / 0 字
import sys
import sqlite3
from hashlib import sha256
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QLabel,
                            QLineEdit, QPushButton, QMessageBox, QTableWidget,
                            QTableWidgetItem, QVBoxLayout, QHBoxLayout, QHeaderView, QComboBox)

class Database:
    def __init__(self):
        self.conn = sqlite3.connect('students.db')
        self.create_tables()

    def add_student(self, name, student_id, age, gender, score):
        try:
            cursor = self.conn.cursor()
            cursor.execute('''INSERT INTO students
                            (name, student_id, age, gender, score)
                            VALUES (?, ?, ?, ?, ?)''',
                           (name, student_id, age, gender, score))
            self.conn.commit()
            return True
        except sqlite3.IntegrityError:
            QMessageBox.warning(None, '错误', '学号已存在!')
            return False

    def delete_student(self, student_id):
        cursor = self.conn.cursor()
        cursor.execute("DELETE FROM students WHERE id=?", (student_id,))
        self.conn.commit()
        return cursor.rowcount > 0
    def create_tables(self):
        cursor = self.conn.cursor()
        # 创建用户表
        cursor.execute('''CREATE TABLE IF NOT EXISTS users (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        username TEXT UNIQUE NOT NULL,
                        password TEXT NOT NULL)''')
        # 创建学生信息表
        cursor.execute('''CREATE TABLE IF NOT EXISTS students (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        name TEXT NOT NULL,
                        student_id TEXT UNIQUE NOT NULL,
                        age INTEGER,
                        gender TEXT,
                        score REAL)''')
        self.conn.commit()

        def update_student(self, student_id, name, new_student_id, age, gender, score):
            try:
                cursor = self.conn.cursor()
                cursor.execute('''UPDATE students SET
                                name=?,
                                student_id=?,
                                age=?,
                                gender=?,
                                score=?
                                WHERE id=?''',
                               (name, new_student_id, age, gender, score, student_id))
                self.conn.commit()
                return True
            except sqlite3.IntegrityError:
                QMessageBox.warning(None, '错误', '学号已存在!')
                return False

    def register_user(self, username, password):
        hashed = sha256(password.encode()).hexdigest()
        try:
            cursor = self.conn.cursor()
            cursor.execute("INSERT INTO users (username, password) VALUES (?, ?)",
                         (username, hashed))
            self.conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False

    def check_login(self, username, password):
        hashed = sha256(password.encode()).hexdigest()
        cursor = self.conn.cursor()
        cursor.execute("SELECT * FROM users WHERE username=? AND password=?",
                      (username, hashed))
        return cursor.fetchone() is not None

class LoginWindow(QMainWindow):
    def __init__(self, db):
        super().__init__()
        self.db = db
        self.initUI()

    def initUI(self):
        self.setWindowTitle('学生管理系统 - 登录')
        self.setGeometry(300, 300, 300, 200)

        layout = QVBoxLayout()

        self.username = QLineEdit()
        self.username.setPlaceholderText('用户名')
        self.password = QLineEdit()
        self.password.setPlaceholderText('密码')
        self.password.setEchoMode(QLineEdit.Password)

        login_btn = QPushButton('登录')
        login_btn.clicked.connect(self.login)
        register_btn = QPushButton('注册')
        register_btn.clicked.connect(self.show_register)

        layout.addWidget(QLabel('用户名:'))
        layout.addWidget(self.username)
        layout.addWidget(QLabel('密码:'))
        layout.addWidget(self.password)
        layout.addWidget(login_btn)
        layout.addWidget(register_btn)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def login(self):
        username = self.username.text()
        password = self.password.text()
        if self.db.check_login(username, password):
            self.main_window = MainWindow(self.db)
            self.main_window.show()
            self.close()
        else:
            QMessageBox.warning(self, '错误', '用户名或密码错误!')

    def show_register(self):
        self.register_window = RegisterWindow(self.db)
        self.register_window.show()

class RegisterWindow(QWidget):
    def __init__(self, db):
        super().__init__()
        self.db = db
        self.initUI()

    def initUI(self):
        self.setWindowTitle('注册')
        self.setGeometry(350, 350, 300, 200)

        layout = QVBoxLayout()

        self.username = QLineEdit()
        self.password = QLineEdit()
        self.password.setEchoMode(QLineEdit.Password)
        self.confirm_pw = QLineEdit()
        self.confirm_pw.setEchoMode(QLineEdit.Password)

        register_btn = QPushButton('注册')
        register_btn.clicked.connect(self.register)

        layout.addWidget(QLabel('用户名:'))
        layout.addWidget(self.username)
        layout.addWidget(QLabel('密码:'))
        layout.addWidget(self.password)
        layout.addWidget(QLabel('确认密码:'))
        layout.addWidget(self.confirm_pw)
        layout.addWidget(register_btn)

        self.setLayout(layout)

    def register(self):
        username = self.username.text()
        password = self.password.text()
        confirm_pw = self.confirm_pw.text()

        if not username or not password:
            QMessageBox.warning(self, '错误', '用户名和密码不能为空!')
            return
        if password != confirm_pw:
            QMessageBox.warning(self, '错误', '两次输入的密码不一致!')
            return

        if self.db.register_user(username, password):
            QMessageBox.information(self, '成功', '注册成功!')
            self.close()
        else:
            QMessageBox.warning(self, '错误', '用户名已存在!')

# 添加学生对话框
class AddStudentDialog(QWidget):
    def __init__(self, db):
        super().__init__()
        self.db = db
        self.initUI()

    def initUI(self):
        self.setWindowTitle('添加学生')
        self.setGeometry(500, 500, 300, 250)

        layout = QVBoxLayout()

        self.name = QLineEdit()
        self.student_id = QLineEdit()
        self.age = QLineEdit()
        self.gender = QComboBox()
        self.gender.addItems(['男', '女'])
        self.score = QLineEdit()

        submit_btn = QPushButton('提交')
        submit_btn.clicked.connect(self.submit)

        layout.addWidget(QLabel('姓名:'))
        layout.addWidget(self.name)
        layout.addWidget(QLabel('学号:'))
        layout.addWidget(self.student_id)
        layout.addWidget(QLabel('年龄:'))
        layout.addWidget(self.age)
        layout.addWidget(QLabel('性别:'))
        layout.addWidget(self.gender)
        layout.addWidget(QLabel('成绩:'))
        layout.addWidget(self.score)
        layout.addWidget(submit_btn)

        self.setLayout(layout)

    def submit(self):
        # 输入验证
        try:
            name = self.name.text().strip()
            student_id = self.student_id.text().strip()
            age = int(self.age.text())
            gender = self.gender.currentText()
            score = float(self.score.text())
        except ValueError:
            QMessageBox.warning(self, '输入错误', '请输入有效的年龄和成绩')
            return

        if not name or not student_id:
            QMessageBox.warning(self, '错误', '姓名和学号不能为空!')
            return

        if self.db.add_student(name, student_id, age, gender, score):
            QMessageBox.information(self, '成功', '学生添加成功!')
            self.close()


# 编辑对话框(复用添加对话框)
class EditStudentDialog(AddStudentDialog):
    def __init__(self, db, student_data):
        super().__init__(db)
        self.setWindowTitle('编辑学生')
        self.student_data = student_data
        self.load_data()

    def load_data(self):
        self.name.setText(self.student_data[1])
        self.student_id.setText(self.student_data[2])
        self.age.setText(str(self.student_data[3]))
        self.gender.setCurrentText(self.student_data[4])
        self.score.setText(str(self.student_data[5]))

    def submit(self):
        # 重写提交逻辑
        try:
            name = self.name.text().strip()
            new_student_id = self.student_id.text().strip()
            age = int(self.age.text())
            gender = self.gender.currentText()
            score = float(self.score.text())
        except ValueError:
            QMessageBox.warning(self, '输入错误', '请输入有效的年龄和成绩')
            return

        if self.db.update_student(self.student_data[0], name, new_student_id,
                                 age, gender, score):
            QMessageBox.information(self, '成功', '修改成功!')
            self.close()

class MainWindow(QMainWindow):
    def __init__(self, db):
        super().__init__()
        self.db = db
        self.initUI()
        self.load_data()
        self.table.cellDoubleClicked.connect(self.edit_student)
    def initUI(self):
        self.setWindowTitle('学生信息管理')
        self.setGeometry(400, 400, 800, 600)

        # 创建表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(['ID', '姓名', '学号', '年龄', '成绩'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 创建操作按钮
        add_btn = QPushButton('添加学生')
        add_btn.clicked.connect(self.add_student)
        delete_btn = QPushButton('删除学生')
        delete_btn.clicked.connect(self.delete_student)

        # 布局
        layout = QVBoxLayout()
        btn_layout = QHBoxLayout()
        btn_layout.addWidget(add_btn)
        btn_layout.addWidget(delete_btn)

        layout.addLayout(btn_layout)
        layout.addWidget(self.table)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

    def load_data(self):
        cursor = self.db.conn.cursor()
        cursor.execute("SELECT * FROM students")
        students = cursor.fetchall()

        self.table.setRowCount(len(students))
        for row, student in enumerate(students):
            for col, data in enumerate(student):
                self.table.setItem(row, col, QTableWidgetItem(str(data)))

    def add_student(self):
        self.add_dialog = AddStudentDialog(self.db)
        self.add_dialog.show()
        self.add_dialog.closeEvent = lambda event: self.load_data()

    def delete_student(self):
        selected = self.table.currentRow()
        if selected == -1:
            QMessageBox.warning(self, '错误', '请先选择要删除的学生')
            return

        student_id = self.table.item(selected, 0).text()
        reply = QMessageBox.question(self, '确认删除',
                                    '确定要删除该学生记录吗?',
                                    QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            if self.db.delete_student(student_id):
                self.load_data()
                QMessageBox.information(self, '成功', '删除成功!')
            else:
                QMessageBox.warning(self, '错误', '删除失败')

    def edit_student(self, row):
        student_id = self.table.item(row, 0).text()
        cursor = self.db.conn.cursor()
        cursor.execute("SELECT * FROM students WHERE id=?", (student_id,))
        student_data = cursor.fetchone()

        self.edit_dialog = EditStudentDialog(self.db, student_data)
        self.edit_dialog.show()
        self.edit_dialog.closeEvent = lambda event: self.load_data()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    db = Database()
    login_window = LoginWindow(db)
    login_window.show()
    sys.exit(app.exec_())

0

评论区