Student performance management system (Python+database)

Student Performance Management System

foreword

A simple student performance management system is implemented with Python and database, let's take a look!

This blog is mainly divided into two parts, the database part and the Python programming part. First import the data into the database, and then connect to the database through python programming to realize a series of operations.

MySQL section

1. Import information

The following is a complete program for creating user tables, student tables, course tables, and grade tables in MySQL language, which can be directly imported into the database.

-- ----------------------------
-- Table structure for `users`
-- ----------------------------
CREATE TABLE `users` (
  `username` varchar(20),
  `passwords` varchar(20),
  PRIMARY KEY(username)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO users VALUES ('user01', '123');

-- ----------------------------
-- Table structure for `student`
-- ----------------------------
CREATE TABLE `student` (
  `sno` char(7) NOT NULL,
  `sname` char(10) NOT NULL,
  `ssex` enum('男','女') DEFAULT '男',
  `sage` tinyint(3) unsigned DEFAULT NULL,
  `sdept` char(20) DEFAULT '计算机科学与工程学院',
  PRIMARY KEY (`sno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO student VALUES ('9512101', '李勇', '男', '19', '计算机系');
INSERT INTO student VALUES ('9512103', '王敏', '女', '20', '计算机系');
INSERT INTO student VALUES ('9513101', '周璐', '女', '17', '物理系');
INSERT INTO student VALUES ('9521101', '张莉', '女', '22', '计算机系');
INSERT INTO student VALUES ('9521102', '吴宾', '男', '21', '计算机系');
INSERT INTO student VALUES ('9521103', '张海', '男', '20', '计算机系');
INSERT INTO student VALUES ('9531101', '钱小平', '女', '18', '数学系');
INSERT INTO student VALUES ('9531102', '王大力', '男', '19', '数学系');
INSERT INTO student VALUES ('9531103', '刘梅', '女', '19', '计算机系');
-- ----------------------------
-- Table structure for `course`
-- ----------------------------
CREATE TABLE `course` (
  `cno` char(4) NOT NULL,
  `cname` varchar(40) NOT NULL,
  `cpno` char(4) DEFAULT NULL,
  `ccredit` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`cno`),
  KEY `cpno` (`cpno`),
  CONSTRAINT `course_ibfk_1` FOREIGN KEY (`cpno`) REFERENCES `course` (`cno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO course VALUES ('C001', '计算机导论', null, '3');
INSERT INTO course VALUES ('C002', '高等数学', null, '4');
INSERT INTO course VALUES ('C003', '程序设计语言', 'C001', '4');
INSERT INTO course VALUES ('C004', '数据结构与算法', 'C003', '5');
INSERT INTO course VALUES ('C005', '数据库原理与应用', 'C004', '4');

-- ----------------------------
-- Table structure for `sc`
-- ----------------------------
CREATE TABLE `sc` (
  `sno` char(7) NOT NULL DEFAULT '',
  `cno` char(4) NOT NULL DEFAULT '',
  `grade` decimal(5,1) DEFAULT NULL,
  PRIMARY KEY (`sno`,`cno`),
  KEY `sno`(`sno`),
  KEY `cno` (`cno`),
  CONSTRAINT `sc_ibfk_1` FOREIGN KEY (`sno`) REFERENCES `student` (`sno`),
  CONSTRAINT `sc_ibfk_2` FOREIGN KEY (`cno`) REFERENCES `course` (`cno`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of sc
-- ----------------------------
INSERT INTO sc VALUES ('9512101', 'C001', null);
INSERT INTO sc VALUES ('9512101', 'C002', '87.0');
INSERT INTO sc VALUES ('9512101', 'C003', '95.0');
INSERT INTO sc VALUES ('9512101', 'C004', '76.0');
INSERT INTO sc VALUES ('9512101', 'C005', '80.0');
INSERT INTO sc VALUES ('9512103', 'C003', '51.0');
INSERT INTO sc VALUES ('9512103', 'C005', '60.0');
INSERT INTO sc VALUES ('9521101', 'C005', '72.0');
INSERT INTO sc VALUES ('9521102', 'C005', '80.0');
INSERT INTO sc VALUES ('9521103', 'C005', '45.0');

INSERT INTO sc VALUES ('9531101', 'C005', '81.0');
INSERT INTO sc VALUES ('9531101', 'C001', null);
INSERT INTO sc VALUES ('9531101', 'C002', '87.0');
INSERT INTO sc VALUES ('9531101', 'C003', '95.0');
INSERT INTO sc VALUES ('9531101', 'C004', '76.0');

INSERT INTO sc VALUES ('9531102', 'C001', null);
INSERT INTO sc VALUES ('9531102', 'C002', '87.0');
INSERT INTO sc VALUES ('9531102', 'C003', '95.0');
INSERT INTO sc VALUES ('9531102', 'C004', '76.0');
INSERT INTO sc VALUES ('9531102', 'C005', '94.0');

2. Demo instructions

I use the navicat database. Let me demonstrate how to import data into the navicat database.

  1. Create a new database, name it "student", select utf8 as the character set, and click OK.
    create

  2. Open the student database you just created, click "Query", and then click "New Query".
    Inquire

  3. Copy and paste the above MySQL statement into the database, and click Run.
    run

  4. After the program finishes running, click on the table on the left and refresh it, and all the tables created just now will appear.
    surface

Python programming part

1. Connect to the database

programming

import pymysql

Username = ""
Findsno = ""
Findcno = ""


def conn():  # 连接数据库
    db = pymysql.connect(host="localhost", user="root", database="student", charset='utf8')
    return db


def update(sql, *values):  # shift键,单tab
    db1 = conn()
    cursor1 = db1.cursor()
    try:
        cursor1.execute(sql, values)
        db1.commit()
        return 1
    except:
        db1.rollback()
        return 0
    finally:
        cursor1.close()
        db1.close()


def update2(sql):  # shift键,单tab
    db1 = conn()
    cursor1 = db1.cursor()
    try:
        cursor1.execute(sql)
        db1.commit()
        return 1
    except:
        db1.rollback()
        return 0
    finally:
        cursor1.close()
        db1.close()


def query(sql, *keys):
    db2 = conn()
    cursor2 = db2.cursor()
    cursor2.execute(sql, keys)
    rs = cursor2.fetchall()
    cursor2.close()
    db2.close()
    return rs


def query2(sql):
    db3 = conn()
    cursor3 = db3.cursor()
    cursor3.execute(sql)
    rs = cursor3.fetchall()
    row = cursor3.rowcount
    cursor3.close()
    db3.close()
    return rs, row

program analysis

In python, we use the pymysql module to connect to the MySQL database and provide a series of functions to perform database operations. The following is a detailed analysis of each function in the code:

conn() function

This function is used to connect to the MySQL database and returns a database connection object.

update() function

This function is used to execute DML statements (such as INSERT, UPDATE, DELETE, etc.), and placeholder parameters (*values) can be used to replace the parameters in the SQL statement. The function will be automatically replaced to prevent SQL injection attacks.

update2() function

This function is also used to execute DML statements, but there is no need to use placeholder parameters, because there are no parameters in the SQL statement in this case, so it can be executed directly.

query() function

This function is used to execute the SQL query statement, and can use placeholder parameters to replace the parameters in the SQL statement. The function returns all matching result sets (ie fetchall).

query2() function

This function is also used to execute the SQL query statement, but there is no need to use placeholder parameters, because there are no parameters in the SQL statement in this case, so it can be executed directly. The function returns all matching result sets and row counts (ie fetchall and rowcount).

2. Login interface

Effect

Log in

programming

import tkinter as tk
import tkinter.messagebox
import db
import mainWin
import register


# 登录界面
class Login():
    def __init__(self):
        self.root2 = tk.Tk()
        self.root2.title("登陆")
        self.screenwidth = self.root2.winfo_screenwidth()
        self.screenheight = self.root2.winfo_screenheight()
        self.root2.geometry('%dx%d+%d+%d' % (400, 200, (self.screenwidth - 400) / 2, (self.screenheight - 200) / 2))
        self.label = tk.Label(self.root2, text='登录系统', font=("黑体", 25))
        self.label.place(x=125, y=10)
        self.userlabel = tk.Label(self.root2, text="用户名:", font=("黑体", 15))
        self.userlabel.place(x=80, y=60)
        self.userentry = tk.Entry(self.root2)
        self.userentry.place(x=160, y=62)
        self.pwdlabel = tk.Label(self.root2, text="密  码:", font=("黑体", 15))
        self.pwdlabel.place(x=80, y=100)
        self.pwdentry = tk.Entry(self.root2, width=20, show='*')
        self.pwdentry.place(x=160, y=102)
        self.userentry.insert(0, 'user01')
        self.pwdentry.insert(0, '123')
        self.okbutton = tk.Button(self.root2, text='提交', font=10, command=self.openMain)
        self.okbutton.place(x=70, y=140)
        self.cancelbutton = tk.Button(self.root2, text='取消', font=10, command=self.root2.destroy)
        self.cancelbutton.place(x=170, y=140)
        self.addbutton = tk.Button(self.root2, text='注册', font=10, command=self.adduser)
        self.addbutton.place(x=270, y=140)
        self.root2.mainloop()

    def openMain(self):
        username2 = self.userentry.get()
        userpwd2 = self.pwdentry.get()
        if username2.strip() == "" or userpwd2.strip() == "":
            tk.messagebox.showerror("登录失败", "用户名或密码不能为空")
            return False
        else:
            try:
                rs = db.query("select * from users where username = %s and passwords = %s", username2, userpwd2)
                if len(rs) > 0:
                    db.Username = username2
                    self.root2.destroy()
                    mainWin.MainWin()
                else:
                    tk.messagebox.showinfo("ee", "你输入的信息不正确,请重新输入")
            except Exception as e:
                print("登陆异常")
                print(e)

    def adduser(self):
        self.root2.destroy()
        register.Register()

program analysis

This is a user login interface program written in Tkinter. The program is mainly divided into two parts, namely interface design and response event processing.

In the interface design part, the code uses various controls of Tkinter, including Label, Entry, Button, etc., to display and receive user input information. The specific design is as follows:

  1. Create a top-level window root2, and set the title and window size.
  2. Add a Label control on the window to display "login system".
  3. Add two Label controls and two Entry controls to receive the user name and password, and initialize the default values.
  4. Add three Button controls for submitting, canceling, and registering operations.

In the response event processing section, the code uses various functions to implement login and registration functions:

  1. The openMain() function is used to process the submit operation, obtain the user name and password entered by the user, and first verify whether it is empty, and then verify whether it exists in the database. Finally, if the login is successful, it will jump to the main interface, otherwise it will give a corresponding prompt.
  2. The adduser() function is used to process the registration operation. When the user presses the "Register" button, close the current login window (root2) and jump to the registration interface.

The db.py module is also called in the program to implement database operations.

3. Registration interface

Effect

register

programming

import tkinter as tk
import tkinter.messagebox
import db
import login


class Register():
    def __init__(self):
        self.root1 = tk.Tk()
        self.root1.title("新用户注册")
        self.screenwidth = self.root1.winfo_screenwidth()
        self.screenheight = self.root1.winfo_screenheight()
        self.root1.geometry('%dx%d+%d+%d' % (400, 200, (self.screenwidth - 400) / 2, (self.screenheight - 200) / 2))
        self.label = tk.Label(self.root1, text='注册系统', font=("黑体", 25))
        self.label.place(x=125, y=10)
        self.userlabel = tk.Label(self.root1, text="用户名:", font=("黑体", 15))
        self.userlabel.place(x=80, y=60)
        self.userentry = tk.Entry(self.root1)
        self.userentry.place(x=160, y=62)
        self.pwdlabel = tk.Label(self.root1, text="密  码:", font=("黑体", 15))
        self.pwdlabel.place(x=80, y=100)
        self.pwdentry = tk.Entry(self.root1, width=20, show='*')
        self.pwdentry.place(x=160, y=102)
        self.okbutton = tk.Button(self.root1, text='提交', font=("黑体", 15), command=self.addUser)
        self.okbutton.place(x=70, y=140)
        self.cancelbutton = tk.Button(self.root1, text='取消', font=("黑体", 15), command=self.root1.destroy)
        self.cancelbutton.place(x=170, y=140)
        self.loginbutton = tk.Button(self.root1, text='登陆', font=("黑体", 15), command=self.loginUser)
        self.loginbutton.place(x=270, y=140)
        self.root1.mainloop()

    def addUser(self):
        username1 = self.userentry.get()
        userpwd1 = self.pwdentry.get()
        if username1.strip() == "" or userpwd1.strip() == "":
            tk.messagebox.showerror("警告", "用户名或密码不能为空")
            return False
        else:
            rs1 = db.query('select * from users where username=%s', username1)
            if len(rs1) > 0:
                tk.messagebox.showinfo("注册失败", "该用户名已经存在")
                self.userentry.delete(0)
                self.pwdentry.delete(0)
            else:
                rs = db.update("insert into users(username,passwords) values(%s,%s)", username1, userpwd1)
                if rs > 0:
                    tk.messagebox.showinfo("用户", "添加成功")
                else:
                    self.userentry.delete(0)
                    self.pwdentry.delete(0)

    def loginUser(self):
        self.root1.destroy()
        login.Login()

program analysis

This is a user registration interface program written in Tkinter. The program is mainly divided into two parts, namely interface design and response event processing.

In the interface design part, the code uses various controls of Tkinter, including Label, Entry, Button, etc., to display and receive user input information. The specific design is as follows:

  1. Create a top-level window root1, and set the title and window size.
  2. Add a Label control to the window to display "Registration System".
  3. Add two Label controls and two Entry controls for receiving username and password.
  4. Add three Button controls for submitting, canceling, and logging in.

In the response event processing section, the code uses various functions to implement user registration and login functions:

  1. The addUser() function is used to process the submit operation, obtain the user name and password entered by the user, and verify whether it is empty first, and then verify whether it already exists in the database. Finally, insert the username and password into the database, and give corresponding prompts.
  2. The loginUser() function is used to process the login operation. When the user presses the "Login" button, the current login window (root1) will be closed and the login interface will be redirected.

The db.py module is also called in the program to implement database operations.

4. Main interface

Effect

Main interface

programming

import tkinter as tk
import numpy as np
import register
import selUser
import login
import findSno
import updPwd
import findCno
import db


class MainWin():
    def __init__(self):
        self.root3 = tk.Tk()
        self.root3.title("成绩分析")
        self.screenwidth = self.root3.winfo_screenwidth()
        self.screenheight = self.root3.winfo_screenheight()
        self.root3.geometry('%dx%d+%d+%d' % (500, 300, (self.screenwidth - 500) / 2, (self.screenheight - 300) / 2))
        menu1 = tk.Menu(self.root3)
        menu1_2 = tk.Menu(menu1, tearoff=False)  # 创建二级菜单
        menu1.add_cascade(label="用户管理", menu=menu1_2)  # 创建级联菜单
        menu1_2.add_command(label='用户注册', command=self.adduser)
        menu1_2.add_command(label='密码修改', command=self.updPwd)
        menu1_2.add_command(label='查询用户信息', command=self.seluser)
        menu1_2.add_command(label='重新登录', command=self.loginuser)
        menu1.add_command(label='退出系统', command=self.root3.quit)
        self.root3.config(menu=menu1_2)
        self.root3.config(menu=menu1)  # 显示菜单

        self.finds = tk.Label(self.root3, text='成绩分析', font=("黑体", 20))
        self.finds.place(x=180, y=30)

        self.student_sno = tk.Label(self.root3, text='请输入要查询成绩的学生学号:', font=("黑体", 12))
        self.student_sno.place(x=50, y=100)
        self.entry_sno = tk.Entry(self.root3)
        self.entry_sno.place(x=280, y=100)
        self.find_sgrade = tk.Button(self.root3, text='查询', font=("黑体", 15), command=self.findsno)
        self.find_sgrade.place(x=200, y=130)

        self.student_cno = tk.Label(self.root3, text='请输入要查询成绩的课程代号:', font=("黑体", 12))
        self.student_cno.place(x=50, y=200)
        self.entry_cno = tk.Entry(self.root3)
        self.entry_cno.place(x=280, y=200)
        self.find_cgrade = tk.Button(self.root3, text='查询', font=("黑体", 15), command=self.findcno)
        self.find_cgrade.place(x=200, y=230)

        self.root3.mainloop()

    def adduser(self):
        self.root3.destroy()
        register.Register()

    def loginuser(self):
        self.root3.destroy()
        login.Login()

    def seluser(self):
        selUser.SelUser()

    def updPwd(self):
        self.root3.destroy()
        updPwd.UpdPWD()

    def findsno(self):
        fsno = self.entry_sno.get()
        snos = np.array(db.query("select sno from sc"))[:, 0]
        if fsno.strip() not in snos:
            tk.messagebox.showerror("警告", "该用户不存在成绩!")
            return False
        else:
            db.Findsno = fsno
            findSno.Manage()

    def findcno(self):
        fcno = self.entry_cno.get()
        cnos = np.array(db.query("select grade from sc where cno=%s and grade is not null", fcno))
        print(cnos)
        if len(cnos) == 0:
            tk.messagebox.showerror("警告", "该课程不存在成绩!")
            return False
        else:
            db.Findcno = fcno
            findCno.Manage()

program analysis

This is a score analysis interface program written in Tkinter. The program is mainly divided into two parts, namely interface design and response event processing.

In the interface design part, the code uses various controls of Tkinter, including Label, Entry, Button, etc., to display and receive user input information, and also adds a menu bar to manage user information. The specific design is as follows:

  1. Create a top-level window root3, and set the title and window size.
  2. Create a menu bar menu1, and add a cascade menu menu1_2, including user registration, password modification, user information query and re-login functions.
  3. Add a Label control to display "Score Analysis".
  4. Add two Label controls and two Entry controls to receive student ID and course code.
  5. Add two Button controls, which are used to query student grades and course grades respectively.

In the response event processing part, the code uses various functions to achieve various functions:

  1. The adduser() function is used to process the user registration operation. When the user presses the "User Registration" button, close the current score analysis window (root3) and jump to the registration interface.
  2. The loginuser() function is used to handle the re-login operation. When the user presses the "Re-login" button, close the current score analysis window (root3) and return to the login interface.
  3. The seluser() function is used to process the operation of querying user information. When the user presses the "Query User Information" button, a pop-up window displays user information.
  4. The updPwd() function is used to process the password change operation. When the user presses the "Password Change" button, the current score analysis window (root3) will be closed and the password change interface will be jumped to.
  5. The findsno() function is used to process the operation of querying student grades, obtain the student number entered by the user, and first verify whether the student number exists in the database, if it exists, pass the student number to the interface for querying student grades, and if it does not exist, give Prompt accordingly.
  6. The findcno() function is used to process the operation of querying course grades, obtain the course code input by the user, first verify whether the course code exists in the database, if it exists, pass the course code to the interface for querying course grades, and give it if it does not exist Prompt accordingly.

db.py is also called in the program.

5. Query information

Effect

Inquire

programming

import tkinter as tk
import tkinter.ttk as ttk
import db


class SelUser():
    def __init__(self):
        self.root4 = tk.Tk()  # 创建根窗口
        self.root4.title("查询用户信息")  # 设置窗口标题
        self.screenwidth = self.root4.winfo_screenwidth()
        self.screenheight = self.root4.winfo_screenheight()
        self.root4.geometry('%dx%d+%d+%d' % (400, 250, (self.screenwidth - 400) / 2, (self.screenheight - 250) / 2))
        self.create_gui()  # 调用窗口组件函数
        self.root4.mainloop()  # 让程序继续执行,直到窗口关闭

    def create_gui(self):  # 定义图形用户界面函数
        self.create_top_right_labelframe()  # 查询条件组件设置
        self.create_records_treeview()  # 查询结果树形菜单组件设置

    def create_top_right_labelframe(self):  # 查询条件组件界面
        labelframe1 = tk.LabelFrame(self.root4, text='用户信息', width=400)  # 标签框架组件
        labelframe1.grid(row=0, column=1, sticky='ew', padx=8, pady=8)

        tk.Label(labelframe1, text='  账号:').grid(row=1, column=1, sticky='w', pady=2)  # 账号标签

        self.namefield = tk.Entry(labelframe1)  # 账号输入框
        self.namefield.grid(row=1, column=2, sticky='w', padx=5, pady=2)

        tk.Label(labelframe1, text='  密码:').grid(row=2, column=1, sticky='w', pady=2)

        self.numfield = tk.Entry(labelframe1)
        self.numfield.grid(row=2, column=2, sticky='w', padx=5, pady=2)

        tk.Button(labelframe1, text='查询', command=self.seluser).grid(row=3, column=1, sticky='e', padx=5, pady=2)

    def create_records_treeview(self):  # 显示记录信息
        treeview_columns = ['userId', 'userName', 'userPwd']
        self.record_treeview = ttk.Treeview(self.root4, show='headings', height=5, columns=treeview_columns)
        self.record_treeview.grid(row=4, column=0, columnspan=3)

        self.record_treeview.heading('userId', text='序号')
        self.record_treeview.heading('userName', text='用户名')
        self.record_treeview.heading('userPwd', text='密码')  # , anchor='center'

        self.record_treeview.column('userId', width=100)
        self.record_treeview.column('userName', width=120)
        self.record_treeview.column('userPwd', width=220)

    def seluser(self):
        username3 = self.namefield.get()
        userpwd3 = self.numfield.get()
        if username3.strip() == "" or userpwd3.strip() == "":
            tk.messagebox.showerror("警告", "用户名或密码不能为空")
            return False
        else:
            rs, row = db.query2(
                "select * from users where username like '%" + username3 + "%' and passwords like '%" + userpwd3 + "%'")
            if row == 0:
                tk.messagebox.showerror("警告", "该用户名或密码不存在")
                return False
            else:
                for i in range(row):
                    self.record_treeview.insert("", 'end', values=rs[i])

program analysis

This code is a window for querying user information, using tkinter to create a GUI interface, and using MySQL database for data query. These include the following functions:

  1. __init__(self)
  • create root window
  • set window title
  • Get screen width and height
  • Call create_gui() to create window components
  • Execute mainloop() to let the program continue to execute
  1. create_gui(self)
  • Call create_top_right_labelframe() to create query condition components
  • Call create_records_treeview() to create the query result tree menu component
  1. create_top_right_labelframe(self)
  • Create a label frame component
  • Create account and password labels
  • Create input box and query button
  • Bind the query button to the seluser() function
  1. create_records_treeview(self)
  • Create a tree menu component
  • Set the columns and titles displayed in the tree menu
  • Set the width of each column of the tree menu
  1. seluser(self)
  • Obtain the entered account and password information
  • Determine whether the input is empty, if it is empty, a pop-up window will warn
  • If the input is not empty, call the db.query2 function to query the database
  • If the query result is empty, pop-up warning
  • If the query result is not empty, traverse the query result and add it to the tree menu

Summary: This code mainly uses tkinter and MySQL to realize the function of querying user information, and uses the GUI interface for operation and display.

6. Change password

Effect

change Password

programming

import tkinter as tk
import tkinter.messagebox
import db
import mainWin


class UpdPWD():
    def __init__(self):
        self.aa = db.Username
        self.root6 = tk.Tk()
        self.screenwidth = self.root6.winfo_screenwidth()
        self.screenheight = self.root6.winfo_screenheight()
        self.root6.geometry('%dx%d+%d+%d' % (400, 200, (self.screenwidth - 400) / 2, (self.screenheight - 200) / 2))
        self.root6.title("密码修改窗口")
        self.namelabel = tk.Label(self.root6, text='账号:', font=("黑体", 15))
        self.namelabel.place(x=80, y=20)
        self.nametxt = tk.Entry(self.root6)
        self.nametxt.place(x=140, y=22)
        self.nametxt.insert(0, self.aa)

        self.labelpwd1 = tk.Label(self.root6, text='密码:', font=("黑体", 15))
        self.labelpwd1.place(x=80, y=60)
        self.pwd1 = tk.Entry(self.root6)
        self.pwd1.place(x=140, y=62)

        self.labelpwd2 = tk.Label(self.root6, text='确认密码:', font=("黑体", 12))
        self.labelpwd2.place(x=60, y=100)
        self.pwd2 = tk.Entry(self.root6)
        self.pwd2.place(x=140, y=102)

        self.button = tk.Button(self.root6, text="确定", font=("黑体", 15), command=self.updpwd)
        self.button.place(x=100, y=140)
        self.button2 = tk.Button(self.root6, text="主窗口", font=("黑体", 15), command=self.returnwin)
        self.button2.place(x=200,y=140)
        self.root6.mainloop()

    def updpwd(self):
        bb = self.pwd1.get()
        aa = self.aa
        print(aa)
        print(bb)
        rs = db.update2("update tb_user set username='" + bb + "' where passwords='" + aa + "'")
        print(rs)
        if rs > 0:
            tk.messagebox.showinfo("提示消息", "密码修改成功")
        else:
            tk.messagebox.showinfo("提示消息", "修改失败")
            self.pwd1.delete(0)
            self.pwd2.delete(0)

    def returnwin(self):
        self.root6.destroy()
        mainWin.MainWin()

program analysis

This is a password modification window class (UpdPWD) based on the tkinter GUI library.

First, in the constructor of the class, the class initializes the interface window (self.root6), sets the window title and size, and creates and places a label (Label) and an input box (Entry).

Then, in the updpwd() method, this class obtains the new password in the input box, and updates it to the account corresponding to the original password by performing a database update operation (update2()). If the update is successful, a "password "Modification successful" prompt box, otherwise the "Modification failed" prompt box will pop up, and the password input box will be cleared.

Finally, in the returnwin() method, the class closes the current window and opens the main window (MainWin).

In general, this class implements the basic functions of the password modification window, and performs data update operations by calling the database, and adds error message and return to the main window button. At the same time, the code structure of this class is relatively clear, easy to understand and maintain.

7. Score Analysis

7.1 Query results by student number

Effect

Grade 1

programming

import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import db
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


class Manage():
    def __init__(self):
        matplotlib.use("TkAgg")
        self.root7 = tk.Tk()
        self.root7.title("学生成绩分析")
        self.screenwidth = self.root7.winfo_screenwidth()
        self.screenheight = self.root7.winfo_screenheight()
        self.root7.geometry('%dx%d+%d+%d' % (400, 350, (self.screenwidth - 400) / 2, (self.screenheight - 350) / 2))
        f = Figure(figsize=(5, 4), dpi=85)
        a = f.add_subplot(111)
        find_name = db.Findsno
        data = db.query("select * from sc where %s=sno and grade is not null", find_name)
        x = np.array(data)[:, 1]
        y = np.array(data)[:, 2].astype(int)
        a.plot(x, y, marker='o', color='red', label='成绩')
        for m, n in zip(x, y):
            a.text(m, n, n, ha='center', va='bottom', fontsize=12)
        a.set_title("学生%s成绩情况折线图" % find_name, fontsize=12)
        a.set_yticks(np.arange(0, 105, 10))
        a.set_xlabel("课程号", fontsize=12)
        a.set_ylabel("成绩", fontsize=12)
        a.legend(loc='lower right')

        canvas = FigureCanvasTkAgg(f, self.root7)
        canvas.draw()
        canvas.get_tk_widget().pack()
        canvas._tkcanvas.pack()
        self.root7.mainloop()

program analysis

This code is a window for visualizing student grades, using tkinter and matplotlib libraries to create a GUI interface and draw a line chart. The specific analysis is as follows:

  1. init(self)
  • create root window
  • set window title
  • Get screen width and height
  • Create a Figure object, set the graphic size and resolution
  • Call the add_subplot() method to create a subplot
  • Call db.Findsno to get the student ID, call db.query to query the student's grades
  • Store query results in numpy array
  • Call the plot() method to draw a line chart
  • Call the text() method to add labels to each point
  • Call to set properties such as subplot title, x-axis, y-axis label and legend
  • Call the FigureCanvasTkAgg() method to draw the graphics on the GUI interface
  1. canvas.draw()
  • draw graphics
  1. canvas.get_tk_widget().pack()
  • Display the GUI interface
  1. canvas._tkcanvas.pack()
  • Embed the tkinter version of the canvas into the GUI

Summary: This code mainly uses the matplotlib library to draw a line graph, and uses the tkinter library to create a GUI interface, which realizes the function of visualizing student grades, which is convenient for users to view and analyze.

7.2 Query results by course number

Effect

Grade 2

programming

import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
import matplotlib
import db
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


class Manage():
    def __init__(self):
        matplotlib.use("TkAgg")
        self.root5 = tk.Tk()
        self.root5.title("课程成绩分析")
        self.screenwidth = self.root5.winfo_screenwidth()
        self.screenheight = self.root5.winfo_screenheight()
        self.root5.geometry('%dx%d+%d+%d' % (400, 350, (self.screenwidth - 400) / 2, (self.screenheight - 350) / 2))
        f = Figure(figsize=(5, 4), dpi=85)
        a = f.add_subplot(111)
        find_name = db.Findcno
        data = db.query("select * from sc where %s=cno and grade is not null", find_name)
        x = np.array(data)[:, 0]
        y = np.array(data)[:, 2].astype(int)
        a.plot(x, y, marker='o', color='blue', label='成绩')
        for m, n in zip(x, y):
            a.text(m, n, n, ha='center', va='bottom', fontsize=12)
        a.set_title("课程%s成绩情况折线图" % find_name, fontsize=12)
        a.set_yticks(np.arange(0, 105, 10))
        a.set_xlabel("课程号", fontsize=12)
        a.set_ylabel("成绩", fontsize=12)
        a.legend(loc='lower right')

        canvas = FigureCanvasTkAgg(f, self.root5)
        canvas.draw()
        canvas.get_tk_widget().pack()
        canvas._tkcanvas.pack()
        self.root5.mainloop()

program analysis

This code is a window that visualizes course grades, very similar to the window that visualizes student grades. The specific analysis is as follows:

  1. init(self)
  • create root window
  • set window title
  • Get screen width and height
  • Create a Figure object, set the graphic size and resolution
  • Call the add_subplot() method to create a subplot
  • Call db.Findcno to get the course number, call db.query to query the grades of the course
  • Store query results in numpy array
  • Call the plot() method to draw a line chart
  • Call the text() method to add labels to each point
  • Call to set properties such as subplot title, x-axis, y-axis label and legend
  • Call the FigureCanvasTkAgg() method to draw the graphics on the GUI interface
  1. canvas.draw()
  • draw graphics
  1. canvas.get_tk_widget().pack()
  • Display the GUI interface
  1. canvas._tkcanvas.pack()
  • Embed the tkinter version of the canvas into the GUI

Summary: This code is very similar to the window for visualizing student grades. It mainly uses the matplotlib library to draw a line graph, and uses the tkinter library to create a GUI interface, realizing the function of visualizing course grades, which is convenient for users to view and analyze.

7. Main function

import login

#主函数
if __name__ == "__main__":
    login.Login()

end

The student performance management system needs some basics of Python programming, Python data analysis and MySQL database. I believe that after completing this project in person, you must gain a lot!

Guess you like

Origin blog.csdn.net/m0_68111267/article/details/130992721