python based integrated student information management system for teachers and students -- python final design!!!

System introduction

The system uses python language for program design. The main contents of the design can be summarized as follows: the teacher-student integrated student information management system, first of all, the administrator (teacher) adds, deletes, modifies, finds and exports student information (in the form of excel form), and then the student's function is different from that of the administrator. The administrator can also change his password and add a new administrator according to the administrator's account. Students log in through their student ID and the initial password given. Students can check their grades, query and modify the password of their personal account through this system.

System implementation effect

home page

The student login interface and the administrator interface are similar

Student information interface

Administrator operation interface

python library and python interpreter used by the system

system configuration

MySQL: mysql8.0
navicat: navicat 12
Pychart:2021.2 version

Main program code

The code has key comments!!!!!

import pymysql
import xlwt #Export excel
import importlib,sys
importlib.reload(sys)
from tkinter import ttk
import tkinter as tk
from PIL import ImageTk, Image # Background picture
import tkinter.font as tkFont
from tkinter import *  # Graphical interface library
import tkinter.messagebox as messagebox  # pop-up notification

# Initialize initial system interface elements
class StartPage:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy sub interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Student information management system')
        self.window.geometry('300x470')
        #Prevent users from resizing windows
        self.window.resizable(0,0)


        label = Label(self.window, text="Student information management system", font=("Verdana", 20))
        label.pack(pady=100)  # pady=100 interface length

        Button(self.window, text="Administrator login", font=tkFont.Font(size=16), command=lambda: AdminPage(self.window), width=30,
               height=2,
               fg='white', bg='gray', activebackground='black', activeforeground='white').pack()
        Button(self.window, text="Student login", font=tkFont.Font(size=16), command=lambda: StudentPage(self.window), width=30,
               height=2, fg='white', bg='gray', activebackground='black', activeforeground='white').pack()
        Button(self.window, text="Account system", font=tkFont.Font(size=16), command=lambda: AboutPage(self.window),
               width=30,
               height=2,
               fg='white', bg='gray', activebackground='black', activeforeground='white').pack()
        Button(self.window, text='Exit the system', height=2, font=tkFont.Font(size=16), width=30, command=self.window.destroy,
               fg='white', bg='gray', activebackground='black', activeforeground='white').pack()

        self.window.mainloop()  # Main message loop


# Administrator login and exit page
class AdminPage:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Administrator login page')
        self.window.geometry('300x450')
        # Prevent users from resizing
        self.window.resizable(0, 0)

        label = tk.Label(self.window, text='Administrator login', bg='green', font=('Verdana', 20), width=30, height=2)
        label.pack()

        Label(self.window, text='Administrator account:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_username = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory')
        self.admin_username.pack()

        Label(self.window, text='Administrator password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_pass = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.admin_pass.pack()

        Button(self.window, text="land", width=8, font=tkFont.Font(size=12), command=self.login).pack(pady=40)
        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=12), command=self.back).pack()

        self.window.protocol("WM_DELETE_WINDOW", self.back)  # Snap top right close Click
        self.window.mainloop()  # Enter message loop

    # Administrator login
    def login(self):
        print(str(self.admin_username.get()))
        print(str(self.admin_pass.get()))
        admin_pass = None

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456') # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM admin_login_k WHERE admin_id = '%s'" % (self.admin_username.get())  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get list of all records
            results = cursor.fetchall()
            for row in results:
                admin_id = row[0]
                admin_pass = row[1]
                # Print results
                print("admin_id=%s,admin_pass=%s" % (admin_id, admin_pass))
        except:
            print("Error: unable to fecth data")
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')
        db.close()  # Close database connection

        print("Logging in administrator management interface")
        print("self", self.admin_pass)
        print("local", admin_pass)

        if self.admin_pass.get() == admin_pass:
            AdminManage(self.window)  # Enter the administrator operation interface
        else:
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')

    # Administrator exit
    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Student login and exit page
class StudentPage:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Student login')
        self.window.geometry('300x450')
        # Prevent users from resizing
        self.window.resizable(0, 0)

        label = tk.Label(self.window, text='Student login', bg='pink', font=('Verdana', 20), width=30, height=2)
        label.pack()

        Label(self.window, text='Student account number:', font=tkFont.Font(size=14)).pack(pady=25)
        self.student_id = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory')
        self.student_id.pack()

        Label(self.window, text='Student password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.student_pass = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.student_pass.pack()

        Button(self.window, text="land", width=8, font=tkFont.Font(size=12), command=self.login).pack(pady=40)
        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=12), command=self.back).pack()

        self.window.protocol("WM_DELETE_WINDOW", self.back)  # Snap top right close Click
        self.window.mainloop()  # Enter message cycle

    def login(self):
        print(str(self.student_id.get()))
        print(str(self.student_pass.get()))
        stu_pass = None

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')  # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM stu_login_k WHERE stu_id = '%s'" % (self.student_id.get())  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            for row in results:
                stu_id = row[0]
                stu_pass = row[1]
                # Print results
                print("stu_id=%s,stu_pass=%s" % (stu_id, stu_pass))
        except:
            print("Error: unable to fecth data")
            messagebox.showinfo('Warning!', 'Incorrect user name or password!')
        db.close()  # Close database connection

        print("Logging in to the student information view interface")
        print("self", self.student_pass.get())
        print("local", stu_pass)

        if self.student_pass.get() == stu_pass:
            StudentView(self.window, self.student_id.get())  # Enter the student information viewing interface
        else:
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')

    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Administrator operation interface
class AdminManage:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = Tk()  # Declaration of initial box
        self.window.title('Administrator operation interface')
        # Prevent users from resizing
        self.window.resizable(0, 0)

        # Overall regional positioning
        self.frame_left_top = tk.Frame(width=300, height=200)
        self.frame_right_top = tk.Frame(width=200, height=200)
        self.frame_center = tk.Frame(width=500, height=400)
        self.frame_bottom = tk.Frame(width=650, height=50)

        # Define the lower center list area
        self.columns = ("Student ID", "full name", "Gender", "Age","achievement")
        self.tree = ttk.Treeview(self.frame_center, show="headings", height=18, columns=self.columns)
        self.vbar = ttk.Scrollbar(self.frame_center, orient=VERTICAL, command=self.tree.yview)
        # Define tree structure and scroll bar
        self.tree.configure(yscrollcommand=self.vbar.set)

        # Table title
        self.tree.column("Student ID", width=100, anchor='center')  # Represents a column, not displayed
        self.tree.column("full name", width=100, anchor='center')
        self.tree.column("Gender", width=100, anchor='center')
        self.tree.column("Age", width=100, anchor='center')
        self.tree.column("achievement", width=100, anchor='center')

        # Call method to get table content insert
        self.tree.grid(row=0, column=0, sticky=NSEW)
        self.vbar.grid(row=0, column=1, sticky=NS)

        self.id = []
        self.name = []
        self.gender = []
        self.age = []
        self.score = []
        # Open database connection
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM student_k"  # SQL query all student information
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            for row in results:
                self.id.append(row[0])
                self.name.append(row[1])
                self.gender.append(row[2])
                self.age.append(row[3])
                self.score.append(row[4])
            print(self.id)
            print(self.name)
            print(self.gender)
            print(self.age)
            print(self.score)
        except:
            print("Error: unable to fetch data")
            messagebox.showinfo('Warning!', 'Database connection failed!')
        db.close()  # Close database connection

        print("test***********************")
        for i in range(min(len(self.id), len(self.name), len(self.gender), len(self.age), len(self.score))):  # Write data
            self.tree.insert('', i, values=(self.id[i], self.name[i], self.gender[i], self.age[i], self.score[i]))

        for col in self.columns:  # Binding function to make the header sortable
            self.tree.heading(col, text=col,
                              command=lambda _col=col: self.tree_sort_column(self.tree, _col, False))

        # Define top area
        # Define the upper left area
        self.top_title = Label(self.frame_left_top, text="Student information:", font=('Verdana', 10))
        self.top_title.grid(row=0, column=0, columnspan=2, sticky=NSEW, padx=50, pady=10)

        self.left_top_frame = tk.Frame(self.frame_left_top)
        self.var_id = StringVar()  # Declared student ID
        self.var_name = StringVar()  # Declaration name
        self.var_gender = StringVar()  # Declaration of gender
        self.var_age = StringVar()  # Declared age
        self.var_score = StringVar()  # Declare achievements
        # Student ID
        self.right_top_id_label = Label(self.frame_left_top, text="Student No.:", font=('Verdana', 15))
        self.right_top_id_entry = Entry(self.frame_left_top, textvariable=self.var_id, font=('Verdana', 15))
        self.right_top_id_label.grid(row=1, column=0)  # Location setting
        self.right_top_id_entry.grid(row=1, column=1)
        # full name
        self.right_top_name_label = Label(self.frame_left_top, text="full name:", font=('Verdana', 15))
        self.right_top_name_entry = Entry(self.frame_left_top, textvariable=self.var_name, font=('Verdana', 15))
        self.right_top_name_label.grid(row=2, column=0)  # Location setting
        self.right_top_name_entry.grid(row=2, column=1)
        # Gender
        self.right_top_gender_label = Label(self.frame_left_top, text="Gender:", font=('Verdana', 15))
        self.right_top_gender_entry = Entry(self.frame_left_top, textvariable=self.var_gender,
                                            font=('Verdana', 15))
        self.right_top_gender_label.grid(row=3, column=0)  # Location setting
        self.right_top_gender_entry.grid(row=3, column=1)
        # Age
        self.right_top_gender_label = Label(self.frame_left_top, text="Age:", font=('Verdana', 15))
        self.right_top_gender_entry = Entry(self.frame_left_top, textvariable=self.var_age,
                                            font=('Verdana', 15))
        self.right_top_gender_label.grid(row=4, column=0)  # Location setting
        self.right_top_gender_entry.grid(row=4, column=1)
        # achievement
        self.right_top_score_label = Label(self.frame_left_top, text="Results:", font=('Verdana', 15))
        self.right_top_score_entry = Entry(self.frame_left_top, textvariable=self.var_score,
                                            font=('Verdana', 15))
        self.right_top_score_label.grid(row=5, column=0)  # Location setting
        self.right_top_score_entry.grid(row=5, column=1)

        # Define upper right area
        self.right_top_title = Label(self.frame_right_top, text="Operation:", font=('Verdana', 10))

        self.tree.bind('<Button-1>', self.click)  # Left click to get the position
        self.right_top_button1 = ttk.Button(self.frame_right_top, text='New student information', width=20, command=self.new_row)
        self.right_top_button2 = ttk.Button(self.frame_right_top, text='Update selected student information', width=20,
                                            command=self.updata_row)
        self.right_top_button3 = ttk.Button(self.frame_right_top, text='Delete selected student information', width=20,
                                            command=self.del_row)
        self.right_top_button4 = ttk.Button(self.frame_right_top, text='Export as Excel file', width=20,command=self.ex_row)

        # Location setting
        self.right_top_title.grid(row=1, column=0, pady=5)
        self.right_top_button1.grid(row=2, column=0, padx=20, pady=5)
        self.right_top_button2.grid(row=3, column=0, padx=20, pady=5)
        self.right_top_button3.grid(row=4, column=0, padx=20, pady=5)
        self.right_top_button4.grid(row=5, column=0, padx=20, pady=5)

        # Overall regional positioning
        self.frame_left_top.grid(row=0, column=0, padx=2, pady=5)
        self.frame_right_top.grid(row=0, column=1, padx=30, pady=30)
        self.frame_center.grid(row=1, column=0, columnspan=2, padx=4, pady=5)
        self.frame_bottom.grid(row=2, column=0, columnspan=2)

        self.frame_left_top.grid_propagate(0)
        self.frame_right_top.grid_propagate(0)
        self.frame_center.grid_propagate(0)
        self.frame_bottom.grid_propagate(0)

        self.frame_left_top.tkraise()  # Start main menu
        self.frame_right_top.tkraise()  # Start displaying the main menu
        self.frame_center.tkraise()  # Start displaying the main menu
        self.frame_bottom.tkraise()  # Start main menu

        self.window.protocol("WM_DELETE_WINDOW", self.back)  # Snap top right close Click

    def back(self):
        StartPage(self.window)  # Display main window destroy this window

    #Click event
    def click(self, event):
        self.col = self.tree.identify_column(event.x)  # column
        self.row = self.tree.identify_row(event.y)  # that 's ok

        print(self.col)
        print(self.row)
        self.row_info = self.tree.item(self.row, "values")
        self.var_id.set(self.row_info[0])
        self.var_name.set(self.row_info[1])
        self.var_gender.set(self.row_info[2])
        self.var_age.set(self.row_info[3])
        self.var_score.set(self.row_info[4])
        self.right_top_id_entry = Entry(self.frame_left_top, state='disabled', textvariable=self.var_id,
                                        font=('Verdana', 15))

        print('')

    #sort
    def tree_sort_column(self, tv, col, reverse):  # Treeview, column name, arrangement
        l = [(tv.set(k, col), k) for k in tv.get_children('')]
        l.sort(reverse=reverse)  # Sort by sort the list in order
        # rearrange items in sorted positions
        for index, (val, k) in enumerate(l):  # Move by sorted index
            tv.move(k, '', index)
        tv.heading(col, command=lambda: self.tree_sort_column(tv, col, not reverse))  # Rewrite the title so that it is in reverse order

    #New student information
    def new_row(self):
        print('123')
        print(self.var_id.get())
        print(self.id)
        #Judge whether students exist
        if str(self.var_id.get()) in self.id:
            messagebox.showinfo('Warning!', 'This student already exists!')
        else:
            #Air judgment
            if self.var_id.get() != '' and self.var_name.get() != '' and self.var_gender.get() != '' and self.var_age.get() != '' and self.var_score.get() != '':
                # Open database connection
                db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
                cursor = db.cursor()  # Use cursor() method to get operation cursor
                sql = "INSERT INTO student_k(id, name, gender, age, score) \
				       VALUES ('%s', '%s', '%s', '%s', '%s')" % \
                      (self.var_id.get(), self.var_name.get(), self.var_gender.get(), self.var_age.get(), self.var_score.get())  # SQL insert statement
                #sql insert and set initial password
                sqls = "INSERT INTO `stu_login_k` VALUES ('%s', '123456')" % (self.var_id.get())
                try:
                    cursor.execute(sql)  # Execute sql statement
                    cursor.execute(sqls)
                    db.commit()  # Commit to database for execution
                except:
                    db.rollback()  # Rollback on error
                    messagebox.showinfo('Warning!', 'Database connection failed!')
                db.close()  # Close database connection

                self.id.append(self.var_id.get())
                self.name.append(self.var_name.get())
                self.gender.append(self.var_gender.get())
                self.age.append(self.var_age.get())
                self.score.append(self.var_score.get())
                self.tree.insert('', len(self.id) - 1, values=(
                    self.id[len(self.id) - 1], self.name[len(self.id) - 1], self.gender[len(self.id) - 1],
                    self.age[len(self.id) - 1], self.score[len(self.id) - 1]))
                self.tree.update()
                messagebox.showinfo('Tips!', 'Successfully inserted!')
            else:
                messagebox.showinfo('Warning!', 'Please fill in the student data')

    #Modify student information
    def updata_row(self):
        res = messagebox.askyesnocancel('Warning!', 'Update the filled data?')
        if res == True:
            if self.var_id.get() == self.row_info[0]:  # If the student number filled in is consistent with the selected student number
                # Open database connection
                db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
                cursor = db.cursor()  # Use cursor() method to get operation cursor
                sql_update = "UPDATE student_k SET name = '%s', gender = '%s', age = '%s', score = '%s' \
				 WHERE id = '%s'" % (
                    self.var_name.get(), self.var_gender.get(), self.var_age.get(), self.var_id.get(), self.var_score.get())  # SQL insert statement
                try:
                    cursor.execute(sql_update)  # Execute sql statement
                    db.commit()  # Submit to database for execution
                    messagebox.showinfo('Tips!', 'Update succeeded!')
                except:
                    db.rollback()  # Rollback on error
                    messagebox.showinfo('Warning!', 'Update failed, database connection failed!')
                db.close()  # Close database connection

                id_index = self.id.index(self.row_info[0])
                self.name[id_index] = self.var_name.get()
                self.gender[id_index] = self.var_gender.get()
                self.age[id_index] = self.var_age.get()
                self.score[id_index] = self.var_score.get()

                self.tree.item(self.tree.selection()[0], values=(
                    self.var_id.get(), self.var_name.get(), self.var_gender.get(),
                    self.var_age.get(), self.var_score.get()))  # Modify row information
            else:
                messagebox.showinfo('Warning!', 'Student ID cannot be modified!')

    #Delete student information
    def del_row(self):
        res = messagebox.askyesnocancel('Warning!', 'Delete selected data?')
        if res == True:
            print(self.row_info[0])  # Student number selected by the mouse
            print(self.tree.selection()[0])  # Line number
            print(self.tree.get_children())  # All rows
            # Open database connection
            db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
            cursor = db.cursor()  # Use cursor() method to get operation cursor
            sql_delete = "DELETE FROM student_k WHERE id = '%s'" % (self.row_info[0])  # SQL insert statement
            sql_deletes = "DELETE  FROM stu_login_k WHERE stu_id = '%s'" % (self.row_info[0])  # SQL insert statement
            try:
                cursor.execute(sql_delete)  # Execute sql statement
                cursor.execute(sql_deletes)
                db.commit()  # Submit to database for execution
                messagebox.showinfo('Tips!', 'Deletion succeeded!')
            except:
                db.rollback()  # Rollback on error
                messagebox.showinfo('Warning!', 'Delete failed, database connection failed!')
            db.close()  # Close database connection

            id_index = self.id.index(self.row_info[0])
            print(id_index)
            del self.id[id_index]
            del self.name[id_index]
            del self.gender[id_index]
            del self.age[id_index]
            del self.score[id_index]
            print(self.id)
            self.tree.delete(self.tree.selection()[0])  # delete the selected line
            print(self.tree.get_children())

    #Student table export form
    def ex_row(self):
        # Open database connection
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM student_k"  # SQL query all student information
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Reset cursor position
            cursor.scroll(0, mode='absolute')
            # Search all results
            results = cursor.fetchall()

            # Get the data field name in MYSQL
            fields = cursor.description
            workbook = xlwt.Workbook()
            sheet = workbook.add_sheet('table_message', cell_overwrite_ok=True)

            # Write field information
            for field in range(0, len(fields)):
                sheet.write(0, field, fields[field][0])

            # Get and write segment information
            row = 1
            col = 0
            for row in range(1, len(results) + 1):
                for col in range(0, len(fields)):
                    sheet.write(row, col, u'%s' % results[row - 1][col])

            workbook.save(r'D:/readout1.xlsx')
            print("export excel File succeeded!")
        except:
            print("Error: unable to fetch data")
            messagebox.showinfo('Warning!', 'Database connection failed!')
        db.close()  # Close database connection


# Student view information interface
class StudentView:
    def __init__(self, parent_window, student_id):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Student information')
        self.window.geometry('300x480')  # The product here is small x
        # Prevent users from resizing
        self.window.resizable(0, 0)

        label = tk.Label(self.window, text='View student information', bg='silver', font=('Verdana', 20), width=30, height=2)
        label.pack(pady=20)

        self.id = 'Student ID:' + ''
        self.name = 'full name:' + ''
        self.gender = 'Gender:' + ''
        self.age = 'Age:' + ''
        self.score = 'achievement:' + ''

        # Open database connection
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM student_k WHERE id = '%s'" % (student_id)  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            for row in results:
                self.id = 'Student ID:' + row[0]
                self.name = 'full name:' + row[1]
                self.gender = 'Gender:' + row[2]
                self.age = 'Age:' + row[3]
                self.score = 'achievement:' + row[4]
        except:
            print("Error: unable to fetch data")
        db.close()  # Close database connection

        # The data obtained from the database is displayed on the interface
        Label(self.window, text=self.id, font=('Verdana', 12)).pack(pady=5)
        Label(self.window, text=self.name, font=('Verdana', 12)).pack(pady=5)
        Label(self.window, text=self.gender, font=('Verdana', 12)).pack(pady=5)
        Label(self.window, text=self.age, font=('Verdana', 12)).pack(pady=5)
        Label(self.window, text=self.score, font=('Verdana', 12)).pack(pady=5)

        Button(self.window, text="Change Password", width=8, font=tkFont.Font(size=16),
               command=lambda: Changekey(self.window)).pack(pady=25)

        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=16), command=self.back).pack(pady=25)

        self.window.protocol("WM_DELETE_WINDOW", self.back)  # Snap top right close Click
        self.window.mainloop()  # Enter message loop

    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Student changes password
class Changekey:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Student account modification page')
        self.window.geometry('300x550')  # The product here is small x
        # Prevent users from resizing
        self.window.resizable(0, 0)

        label = tk.Label(self.window, text='Change student password', bg='green', font=('Verdana', 20), width=30, height=2)
        label.pack()

        Label(self.window, text='Student No.:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_id = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory')
        self.admin_id.pack()

        Label(self.window, text='Old password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_key = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.admin_key.pack()

        Label(self.window, text='New password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_pass = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.admin_pass.pack()

        Button(self.window, text="Confirm modification", width=8, font=tkFont.Font(size=12), command=self.login).pack(pady=40)
        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=12), command=self.back).pack()

    def login(self):
        print(str(self.admin_id.get()))
        print(str(self.admin_key.get()))
        stu_pass = None
        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')  # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM stu_login_k WHERE stu_id = '%s'" % (self.admin_id.get())  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            for row in results:
                stu_id = row[0]
                stu_pass = row[1]
                # Print results
                print("stu_id=%s,stu_pass=%s" % (stu_id, stu_pass))
        except:
            print("Error: unable to fecth data")
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')
        db.close()  # Close database connection

        print("Modifying")
        print("Old password", self.admin_key.get())
        print("New password", stu_pass)

        if self.admin_key.get() == stu_pass:
            self.chage()
        else:
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')

    def chage(self):
        print(str(self.admin_id.get()))
        print(str(self.admin_key.get()))
        print(str(self.admin_pass.get()))
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "UPDATE stu_login_k SET stu_pass = '%s' WHERE stu_id = '%s'" % (
            self.admin_pass.get(), self.admin_id.get())
        try:
            cursor.execute(sql)  # Execute sql statement
            db.commit()  # Submit to database for execution
            messagebox.showinfo('Tips!', 'Update succeeded!')
        except:
            db.rollback()  # Rollback on error
            messagebox.showinfo('Warning!', 'Update failed, database connection failed!')
        db.close()  # Close database connection

    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Version statement
class AboutPage:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box

        self.window.title('Account system')
        self.window.geometry('300x420')
        # Prevent users from resizing
        self.window.resizable(0, 0)

        label = tk.Label(self.window, text='Account system', bg='cyan', font=('Verdana', 20), width=30, height=2)
        label.pack()

        Label(self.window, text='Student account number is student number', font=('Verdana', 18)).pack(pady=5)
        Label(self.window, text='The initial password is 123456', font=('Verdana', 18)).pack(pady=5)
        Label(self.window, text='Version: 1.0.3', font=('Verdana', 16)).pack(pady=5)

        Button(self.window, text="Change Password", width=10, font=tkFont.Font(size=16),
               command=lambda: Changekey(self.window)).pack(pady=15)
        Button(self.window, text="Administrator modification", width=10, font=tkFont.Font(size=16),
               command=lambda: Adminlogin(self.window)).pack(pady=15)
        Button(self.window, text="Return to the home page", width=10, font=tkFont.Font(size=16), command=self.back).pack(pady=15)

        self.window.protocol("WM_DELETE_WINDOW", self.back)  # Snap top right close Click
        self.window.mainloop()  # Enter message loop

    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Administrator login
class Adminlogin:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Please log in to any administrator account first')
        self.window.geometry('300x500')  # The product here is small x
        # Prevent users from resizing
        self.window.resizable(0, 0)

        label = tk.Label(self.window, text='Administrator login', bg='green', font=('Verdana', 20), width=30, height=2)
        label.pack()

        Label(self.window, text='Administrator account:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_username = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory')
        self.admin_username.pack()

        Label(self.window, text='Administrator password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_pass = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.admin_pass.pack()

        Button(self.window, text="Change Password", width=8, font=tkFont.Font(size=12), command=self.login_change).pack(pady=25)
        Button(self.window, text="Create an account", width=8, font=tkFont.Font(size=12), command=self.login_create).pack(pady=25)
        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=12), command=self.back).pack(pady=25)

        self.window.protocol("WM_DELETE_WINDOW", self.back)  # Snap top right close Click
        self.window.mainloop()  # Enter message loop

    # Add administrator
    def login_create(self):
        print(str(self.admin_username.get()))
        print(str(self.admin_pass.get()))
        admin_pass = None

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student',user='root', password='123456')  # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM admin_login_k WHERE admin_id = '%s'" % (self.admin_username.get())  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            for row in results:
                admin_id = row[0]
                admin_pass = row[1]
                # Print results
                print("admin_id=%s,admin_pass=%s" % (admin_id, admin_pass))
        except:
            print("Error: unable to fecth data")
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')
        db.close()  # Close database connection

        print("Logging in administrator creation interface")
        print("self", self.admin_pass)
        print("local", admin_pass)

        if self.admin_pass.get() == admin_pass:
            CreateAdminPage(self.window)
        else:
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')

    # Administrator changes password
    def login_change(self):
        print(str(self.admin_username.get()))
        print(str(self.admin_pass.get()))
        admin_pass = None

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student',user='root', password='123456')  # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT * FROM admin_login_k WHERE admin_id = '%s'" % (self.admin_username.get())  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            for row in results:
                admin_id = row[0]
                admin_pass = row[1]
                # Print results
                print("admin_id=%s,admin_pass=%s" % (admin_id, admin_pass))
        except:
            print("Error: unable to fecth data")
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')
        db.close()  # Close database connection

        print("Logging in administrator creation interface")
        print("self", self.admin_pass)
        print("local", admin_pass)


        if self.admin_pass.get() == admin_pass:
            AdminChange(self.window)
        else:
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')

    # Destroy Window 
    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Create administrator
class CreateAdminPage:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Administrator account registration')
        self.window.geometry('300x450')  # The product here is small x
        # Prevent users from resizing
        self.window.resizable(0, 0)

        Label(self.window, text='Administrator user name:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_id = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory')
        self.admin_id.pack()

        Label(self.window, text='Set password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_pass = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.admin_pass.pack()

        Button(self.window, text="Create user", width=8, font=tkFont.Font(size=12), command=self.find).pack(pady=40)
        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=12), command=self.back).pack()

    def back(self):
        StartPage(self.window)  # Display main window destroy this window

    def find(self):
        print(str(self.admin_id.get()))
        print(str(self.admin_pass.get()))

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456') # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "SELECT admin_id FROM admin_login_k WHERE admin_id = '%s'" % \
              (self.admin_id.get())  # SQL query statement
        try:
            # Execute SQL statement
            cursor.execute(sql)
            # Get a list of all records
            results = cursor.fetchall()
            print(results)
            if self.admin_id.get in results:
                print("Error: name already exists!")
                messagebox.showinfo('Warning!', 'User name already exists!')
            else:
                self.change()

        except:
            print("Error: unable to fecth data")
            messagebox.showinfo('Warning!', 'The user name or password is incorrect!')

    #Add administrator
    def change(self):
        print(str(self.admin_id.get()))
        print(str(self.admin_pass.get()))

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student',user='root', password='123456') # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "INSERT INTO admin_login_k(admin_id, admin_pass) VALUES ('%s', '%s')" % \
              (self.admin_id.get(), self.admin_pass.get())  # SQL query statement
        try:
            cursor.execute(sql)  # Execute sql statement
            db.commit()  # Submit to database for execution
        except:
            db.rollback()  # Rollback on error
            messagebox.showinfo('Warning!', 'Database connection failed!')

        db.close()  # Close database connection

        messagebox.showinfo('Tips', 'Created successfully')


# Administrator password modification
class AdminChange:
    def __init__(self, parent_window):
        parent_window.destroy()  # Destroy main interface

        self.window = tk.Tk()  # Declaration of initial box
        self.window.title('Administrator password modification')
        self.window.geometry('300x450')  # The product here is small x
        # Prevent users from resizing
        self.window.resizable(0, 0)

        Label(self.window, text='Administrator user name:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_id = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory')
        self.admin_id.pack()

        Label(self.window, text='Set password:', font=tkFont.Font(size=14)).pack(pady=25)
        self.admin_pass = tk.Entry(self.window, width=30, font=tkFont.Font(size=14), bg='Ivory', show='*')
        self.admin_pass.pack()

        Button(self.window, text="Confirm modification", width=8, font=tkFont.Font(size=12), command=self.chage).pack(pady=40)
        Button(self.window, text="Return to the home page", width=8, font=tkFont.Font(size=12), command=self.back).pack()

    def chage(self):
        print(str(self.admin_id.get()))
        print(str(self.admin_pass.get()))

        # Database operation query administrator table
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')  # Open database connection
        cursor = db.cursor()  # Use cursor() method to get operation cursor
        sql = "UPDATE admin_login_k SET admin_pass = '%s' WHERE admin_id = '%s'" % \
              (self.admin_pass.get(), self.admin_id.get())  # SQL query statement
        try:
            cursor.execute(sql)  # Execute sql statement
            db.commit()  # Submit to database for execution
            messagebox.showinfo('Tips!', 'Update succeeded!')
        except:
            db.rollback()  # Rollback on error
            messagebox.showinfo('Warning!', 'Update failed, database connection failed!')
        db.close()  # Close database connection

    def back(self):
        StartPage(self.window)  # Display main window destroy this window


# Create database instantiation Application
if __name__ == '__main__':
    try:
        # Open database connection connection test
        db = pymysql.connect(host='localhost', port=3306, db='student', user='root', password='123456')
        # Use cursor() method to get operation cursor
        cursor = db.cursor()
        # If the data table does not exist, create the table. If it exists, skip
        # Set primary key unique
        sql = """CREATE TABLE IF NOT EXISTS student_k(
				id char(20) NOT NULL,
				name char(20) default NULL,
				gender char(5) default NULL,  
				age char(5) default NULL,
				PRIMARY KEY (id)

				) ENGINE = InnoDB 
				DEFAULT	CHARSET = utf8
				"""
        cursor.execute(sql)
        # Create a table if the data table does not exist skip if it exists
        sql = """CREATE TABLE IF NOT EXISTS admin_login_k(
						admin_id char(20) NOT NULL,
						admin_pass char(20) default NULL,
						PRIMARY KEY (admin_id)
						) ENGINE = InnoDB 
						DEFAULT	CHARSET = utf8
						"""
        cursor.execute(sql)
        # If the data table does not exist, create the table. If it exists, skip
        sql = """CREATE TABLE IF NOT EXISTS stu_login_k(
						stu_id char(20) NOT NULL,
						stu_pass char(20) default NULL,
						PRIMARY KEY (stu_id)
						) ENGINE = InnoDB 
						DEFAULT	CHARSET = utf8
						"""
        cursor.execute(sql)

        # Close database connection
        db.close()

        # Instantiate Application
        window = tk.Tk() # create a window
        StartPage(window) # Call the StartPage method

    except:
        messagebox.showinfo('Error!', 'Failed to connect to the database!')

Database file

SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for `admin_login_k`
-- ----------------------------
DROP TABLE IF EXISTS `admin_login_k`;
CREATE TABLE `admin_login_k` (
  `admin_id` char(20) NOT NULL,
  `admin_pass` char(20) DEFAULT NULL,
  PRIMARY KEY (`admin_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of admin_login_k
-- ----------------------------
INSERT INTO `admin_login_k` VALUES ('admin', 'admin');
 
-- ----------------------------
-- Table structure for `student_k`
-- ----------------------------
DROP TABLE IF EXISTS `student_k`;
CREATE TABLE `student_k` (
  `id` char(20) NOT NULL,
  `name` char(20) DEFAULT NULL,
  `gender` char(5) DEFAULT NULL,
  `age` char(5) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of student_k
-- ----------------------------
INSERT INTO `student_k` VALUES ('209114122', 'Xu Zhiqiang', 'male', '21');
INSERT INTO `student_k` VALUES ('206546845', 'Zhang Hao', 'male', '21');
INSERT INTO `student_k` VALUES ('182085215', 'Tom', 'male', '23');
INSERT INTO `student_k` VALUES ('182085211', 'Jerry', 'male', '21');
INSERT INTO `student_k` VALUES ('182085212', 'Bob', 'male', '24');
INSERT INTO `student_k` VALUES ('182011011', 'Patrick Star', 'male', '23');
INSERT INTO `student_k` VALUES ('209084163', 'Sandy', 'female', '29');
INSERT INTO `student_k` VALUES ('209045599', 'Octopus brother', 'male', '38');
INSERT INTO `student_k` VALUES ('209055599', 'Crab ajin', 'male', '42');
-- ----------------------------
-- Table structure for `stu_login_k`
-- ----------------------------
DROP TABLE IF EXISTS `stu_login_k`;
CREATE TABLE `stu_login_k` (
  `stu_id` char(20) NOT NULL,
  `stu_pass` char(20) DEFAULT NULL,
  PRIMARY KEY (`stu_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of stu_login_k
-- ----------------------------
INSERT INTO `stu_login_k` VALUES ('209114122', '123456');
INSERT INTO `stu_login_k` VALUES ('206546845', '123456');
INSERT INTO `stu_login_k` VALUES ('182085215', '123456');
INSERT INTO `stu_login_k` VALUES ('182085211', '123456');
INSERT INTO `stu_login_k` VALUES ('182085212', '123456');
INSERT INTO `stu_login_k` VALUES ('182011011', '123456');
INSERT INTO `stu_login_k` VALUES ('209084163', '123456');
INSERT INTO `stu_login_k` VALUES ('209045599', '123456');
INSERT INTO `stu_login_k` VALUES ('209055599', '123456');

 
-- ----------------------------
-- Table structure for `t_course`
-- ----------------------------
DROP TABLE IF EXISTS `t_course`;
CREATE TABLE `t_course` (
  `SNO` char(255) NOT NULL,
  `COURSE` char(255) DEFAULT NULL,
  `CREDIT` char(255) DEFAULT NULL,
  `GRADE` char(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of t_course
-- ----------------------------
INSERT INTO `t_course` VALUES ('08300205', 'Programming', '4', '88');
INSERT INTO `t_course` VALUES ('08300205', 'database', '2.5', '90');
INSERT INTO `t_course` VALUES ('08300205', 'python', '5', '92');
INSERT INTO `t_course` VALUES ('08080929', 'database', '2.5', '85');
INSERT INTO `t_course` VALUES ('09350124', 'database', '2.5', '92');
INSERT INTO `t_course` VALUES ('09620233', 'database', '2.5', '80');
INSERT INTO `t_course` VALUES ('09300218', 'database', '2.5', '78');
INSERT INTO `t_course` VALUES ('09010122', 'database', '2.5', '87');
INSERT INTO `t_course` VALUES ('08080929', 'Programming', '4', '86');
INSERT INTO `t_course` VALUES ('09010122', 'Programming', '4', '80');
INSERT INTO `t_course` VALUES ('08300516', 'Programming', '4', '76');
 
-- ----------------------------
-- Table structure for `t_st`
-- ----------------------------
DROP TABLE IF EXISTS `t_st`;
CREATE TABLE `t_st` (
  `SNO` char(11) NOT NULL,
  `SNAME` char(255) DEFAULT NULL,
  `SSEX` char(255) DEFAULT NULL,
  `AGE` char(255) DEFAULT NULL,
  `DEPT` char(255) DEFAULT NULL,
  PRIMARY KEY (`SNO`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of t_st
-- ----------------------------
INSERT INTO `t_st` VALUES ('209044483', 'Wangchenyang', 'male', '20', 'Total 204');

Project summary and experience

When developing this project, I have development experience in developing similar projects, but it is more challenging for me to develop with Python. In addition, the development time of this system is short, the development is more repeatable, and the understanding of customer needs is not very thorough. In summary, I am not very efficient in the development of this project, on the contrary, there is a considerable waste of time. However, after my systematic sorting and according to the needs of teachers, I started from the database, analyzed the data required by each function, and finally completed the design of the database. Then I began to work out the development direction. Finally, I chose the thinter library as the main development library. Tkinter is a module that uses Python to design windows. Tkinter is a GUI interface that comes with Python and can be edited. The reason why I chose Tkinter is that it is the simplest and the library comes with it. You don't need to download and install it at any time. And I mainly use treeview, which is very powerful. First, it is a combination of tree and list. The first column is its tree structure, and the following columns are list structures. Treeview is often used to display hierarchical data. Each data item can have a text, a picture, and multiple column data values. The display sorting of data columns can be set through diplaycolumns, and treeview can also display the header of data columns. Each data item (item) has a unique name and ID. if the ID is not specified when creating an item, it will be automatically generated. Treeview supports horizontal and vertical scrollbars, which can be accessed through xscrollcommand and yscrollcom Mand and treeview xview(),Treeview.yview() setting and control. Finally, when it came to testing, I tested each function twoorthree times to reduce the occurrence rate of bug s. Through the development of this project, I have a new understanding of Python development. I will continue to study Python in depth and experience the learning fun brought by python. It is the so-called "life is short, I use Python!".

Tags: Python SQL numpy

Posted by narch31 on Fri, 01 Jul 2022 21:35:10 +0300