python+mysql+tkinter student information management system

Keywords: Python MySQL Tkinter

requirement analysis

(1) Using mysql to store student and administrator information
(2) The graphical interface is created through tkinter module to realize the login of the administrator, the addition, deletion, modification and query of student information, and the modification of the administrator's own password.

Whole engineering class and method

Database design

Create using mysql database
menege table and student table

Creation of menege table:

create table manege(
	user_name varchr(6) not null,
	user_pwd char(6) not null,
	user_state int(1) not null
	primary key (user_name)
	);

Insert data into table manege:
insert into manege values(admin,123456,1)

student table creation
Creation of reference manege table

Just insert the data

Window design

Login interface


Interface display

Steps:
(1) Create login first_ Page.py module
(2) Create a LoginWindow class in this module, which inherits from Tk

from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import datetime
import mainGUI
import pymysql
import os

class LoginWindow(Tk):
    """To create a login form GUI Interface and login method"""

	#Constructor, which runs automatically after the object is created
    def __init__(self):
        super().__init__() #Initialize tk this class first
        self.title("Student information management system")
        self.resizable(0,0) #The form size cannot be changed. The two parameters represent the x-axis and y-axis respectively
        
        #These three parameters are passed to the next interface
        self.user =""  
        self.pwd=""
        self.state=1

        # Load form
        self.setup_UI()
        self.user_list = [] #Store user information

setup_UI() function:

def setup_UI(self):
        # ttk controls use style object settings
        self.Style01 = Style()
        self.Style01.configure("user.TLabel",font = ("Chinese bold",20,"bold"),foreground = "black")
        self.Style01.configure("TEntry",font = ("Chinese bold",20,"bold"))
        self.Style01.configure("TButton",font = ("Chinese bold",20,"bold"),foreground = "black",bg='red')
        # Create a Label to show the picture
        self.Login_image = PhotoImage(file = "."+os.sep+"images"+os.sep+"back1.png")
        self.Label_image = Label(self,image = self.Login_image,text="Student information management system",compound=BOTTOM,font=("Chinese bold",22,"bold"))
        self.Label_image.pack(padx = 10,pady = 10)
        # Create a Label label + Entry --- user name
        self.Label_user = Label(self,text = "user name:", style = "user.TLabel")
        self.Label_user.pack(side = LEFT,padx = 10,pady = 10)
        self.Entry_user = Entry(self,width = 12)
        self.Entry_user.pack(side = LEFT,padx = 10,pady = 10)
        # Create a Label label + Entry --- password
        self.Label_password = Label(self, text = "password:", style = "user.TLabel")
        self.Label_password.pack(side = LEFT,padx = 10,pady = 10)
        self.Entry_password = Entry(self, width=12,show = "*")
        self.Entry_password.pack(side = LEFT,padx = 10,pady = 10)
        # Create a button - login
        self.Button_login = Button(self,text = "Sign in",width = 4,command=lambda:self.login())
        self.Button_login.pack(side = LEFT,padx = 20,pady = 10)

load_main(self) function

    def load_main(self):
        # Close the current form
        #
        self.destroy()
        # Load new form
        if __name__ == '__main__':
            main_Window = mainGUI.MainWindow(self.user,self.get_now_time(),self.pwd,self.state)
            main_Window.mainloop()

login(self) function

    def login(self):
        # Get user name and password
        user = self.Entry_user.get()
        password = self.Entry_password.get()
        db = pymysql.connect(host="localhost",user="root",passwd="123456",database="student_manegement")
        cursor = db.cursor()
        sql = "select * from manege where user_name=%s"
        cursor.execute(sql,user)
        #Store the obtained administrator data in the list
        self.user_list= cursor.fetchall()
        print(self.user_list)
        cursor.close()
        db.close()
        if len(self.user_list)!=0:
            if 0 == self.user_list[0][2]:
                messagebox.showinfo("System message","The account is disabled, please contact the administrator")
            else:
                if password != str(self.user_list[0][1].strip().lower()):
                    messagebox.showinfo("System message","Wrong password entered")
                else:
                    messagebox.showinfo("System message","Login succeeded!")
                    self.user = self.user_list[0][0]
                    self.pwd = self.user_list[0][1]
                    self.state = self.user_list[0][2]
                    self.load_main()
        else:
            messagebox.showinfo("System message",'The entered user name does not exist')

get_now_time(self) function

def get_now_time(self):
        today = datetime.datetime.today()
        return ("%04d-%02d-%02d %02d:%02d:%02d"%(today.year,today.month,today.day,today.hour,today.minute,today.second))

Create login interface object

if __name__=='__main__':
    this_login = LoginWindow()
    print(this_login.get_now_time())
    this_login.mainloop()

Note: if must be added here__ name__=='__ main__'
Otherwise, you will not jump to the main interface
Causes:
Import the login module on the main page, because the python interpreter executes in order, and the import module is at the top of the program and executed to import login_page, if there is no if__ name__=='__ main__', The login interface will be created, so after the login is successful, jump to the login interface.

main interface


Interface display

Create a new module mainGUI.py module

Constructor

from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import detailGUI
import change_pwd
import login_page
import pymysql
import os
import sys
class MainWindow(Tk):
    
    def __init__(self,login_user,login_time,psw,state):
        super().__init__()
        self.title("Main form")
        self.geometry("1050x640+180+80")
        self.resizable(0,0)
        self["bg"]="cornflowerblue"
        # The administrator login name and login time passed from the login interface
        self.current_user = login_user
        self.current_time = login_time
        self.current_psw = psw
        self.current_state = state
        # Load page UI
        self.setup_UI()

        # Read student information
        self.all_student_list =[] #Use a list to store the read student information
        self.load_file_student_info()

        # Load student information in treeview
        self.load_treeview(self.all_student_list)

        # Define a list that stores query results
        self.query_result_list = []
        
        self.current_student_list=[]
        

setup_UI(self) page layout

    def setup_UI(self):
        # Set Style
        self.Style01 = Style()
        self.Style01.configure("left.TPanedwindow",background ="white")
        self.Style01.configure("right.TPanedwindow",background="white")
        self.Style01.configure("TButton",width = 10,font = ("Chinese bold",15,"bold"),background="white")

        # Top_banner
        self.Login_image = PhotoImage(file="."+os.sep+"images"+os.sep+"shouye.png")
        self.Label_image = Label(self,image=self.Login_image)
        self.Label_image.pack(padx=100,pady=10)
        self.Lable_login_user = Label(self,text="Current user:"+str(self.current_user).title()+"\n Login time:"+self.current_time)
        self.Lable_login_user.place(x=680,y=40)


        # Left: button area, create a container
        self.Pane_left = PanedWindow(width=200,height=541,style="left.TPanedwindow")
        self.Pane_left.place(x=4,y=94)
        self.Pane_right = PanedWindow(width=830,height=540,style="right.TPanedwindow")
        self.Pane_right.place(x=210,y=94)

        # Add left button
        # self.Button_image = PhotoImage(file="."+os.sep+"images"+os.sep+"tianjia.png")
        self.Button_add = Button(self.Pane_left,text="Add student",style="TButton",command=lambda:self.add_studnet())
        self.Button_add.place(x=40,y=20)
        self.Button_update = Button(self.Pane_left,text="Modify student",style="TButton",command=lambda:self.update_student())
        self.Button_update.place(x=40,y=60)
        self.Button_delete = Button(self.Pane_left,text="Delete student",style="TButton",command=lambda:self.delete_student())
        self.Button_delete.place(x=40,y=100)
        self.Button_modify = Button(self.Pane_left,text="Change password",style="TButton",command=lambda:self.change_manege())
        self.Button_modify.place(x=40,y=230)

        # Right: query, TreeView
        # self.Pane_right = PanedWindow(width=725,height=540,style="right.TPanedwindow")
        # self.Pane_right.place(x=170,y=94)
        # LabelFrame
        self.LabelFrame_query = LabelFrame(self.Pane_right,text="Student information query",width=802,height=70)
        self.LabelFrame_query.place(x=10,y=10)

        # add controls
        # Student number
        self.Label_sno = Label(self.LabelFrame_query,text="Student No.:",style=None)
        self.Label_sno.place(x=5,y=13)
        self.Entry_sno = Entry(self.LabelFrame_query,width=8,style=None)
        self.Entry_sno.place(x=60,y=15)

        # full name
        self.Label_name = Label(self.LabelFrame_query,text="full name:",style=None)
        self.Label_name.place(x=125,y=13)
        self.Entry_name = Entry(self.LabelFrame_query,width = 8,style=None)
        self.Entry_name.place(x=180,y=15)

        # Telephone
        self.Label_mobile = Label(self.LabelFrame_query,text="Telephone:")
        self.Label_mobile.place(x=245,y=13)
        self.Entry_mobile = Entry(self.LabelFrame_query,width=8)
        self.Entry_mobile.place(x=300,y=15)

        # college
        self.Label_academy = Label(self.LabelFrame_query,text="College:")
        self.Label_academy.place(x=365,y=13)
        self.Entry_academy = Entry(self.LabelFrame_query,width=8)
        self.Entry_academy.place(x=420,y=15)

        # Query button
        self.Button_query = Button(self.LabelFrame_query,text="query",width=4,command=lambda:self.get_query_result())
        self.Button_query.place(x=520,y=8)
        self.Button_showall = Button(self.LabelFrame_query,text="Show all",width=8,command=lambda:self.load_all_student())
        self.Button_showall.place(x=590,y=8)

        # Add TreeView control
        self.Tree = Treeview(self.Pane_right,columns=("sno","names","academy","gender","birthday","mobile","email","address"),show="headings",height=21)

        # Set the width and alignment of each column
        self.Tree.column("sno",width=100,anchor="center")
        self.Tree.column("names",width=80,anchor="center")
        self.Tree.column("academy",width=120,anchor="center")
        self.Tree.column("gender",width=80,anchor="center")
        self.Tree.column("birthday",width=100,anchor="center")
        self.Tree.column("mobile",width=100,anchor="center")
        self.Tree.column("email",width=100,anchor="center")
        self.Tree.column("address",width=120,anchor="center")

        # Set the title of each column
        self.Tree.heading("sno",text="Student number")
        self.Tree.heading("names",text="full name")
        self.Tree.heading("academy",text="major")
        self.Tree.heading("gender",text="Gender")
        self.Tree.heading("birthday",text="birthday")
        self.Tree.heading("mobile",text="phone number")
        self.Tree.heading("email",text="e-mail address")
        self.Tree.heading("address",text="Home address")

        self.Tree.place(x=10,y=80)
        #Bind the double-click event for the tree, and the details of the clicked students will be displayed after double clicking
        self.Tree.bind("<Double-1>",self.view_student)

load_file_student_info(self) function

    # Read information from file / database
    def load_file_student_info(self):
        # Read information using database
        config={
            "host":"localhost",
            "user":"root",
            "password":"123456",
            "database":"student_manegement"
        }
        db = pymysql.connect(**config)
        cursor = db.cursor()
        sql = "select * from student"
        cursor.execute(sql)
        self.all_student_list = list(cursor.fetchall())
        print("All students found using the function:",len(list(self.all_student_list)))
        cursor.close()
        db.close()

load_ The treeview (self, current_list: list) method loads treeview information

    def load_treeview(self,current_list:list):
        # Judge whether there is data:
        if len(current_list) == 0:
            messagebox.showinfo("System message","No data loaded")
        else:
            for index in range(len(current_list)):
                self.Tree.insert("",index,values=(current_list[index][0],current_list[index][1],
                current_list[index][9],current_list[index][2],current_list[index][3],
                current_list[index][5],current_list[index][6],current_list[index][7]))

get_ query_ The result (self) method implements the query method

        # Prepare query criteria: obtain student number
        query_condition = [self.Entry_sno.get(),self.Entry_name.get(),self.Entry_academy.get(),self.Entry_mobile.get()]
        if len(query_condition[0])==0 and len(query_condition[1])==0 and len(query_condition[2])==0 and len(query_condition[3])==0:
            messagebox.showinfo("System message","Please enter the content to find!")
        else:
            for item in self.all_student_list:
                if query_condition[0] in str(item[0]) and query_condition[1] in item[1] and query_condition[2] in item[9] and query_condition[3] in item[5]:
                    self.query_result_list.append(item)
            for i in self.Tree.get_children():
                self.Tree.delete(i)
            self.load_treeview(self.query_result_list)
            self.query_result_list.clear()

load_all_student(self) method
Click Show all to display and clear the contents in the input box in treeview

    def load_all_student(self):
        for i in self.Tree.get_children():
            self.Tree.delete(i)
        # After clicking the show all button, the input box is cleared
        self.Entry_sno.delete(0,"end")
        self.Entry_name.delete(0,"end")
        self.Entry_academy.delete(0,"end")
        self.Entry_mobile.delete(0,"end")
        # Find all student information
        self.load_file_student_info()
        # Load all student information into TreeView
        self.load_treeview(self.all_student_list)

load_detail_window(self,flag) function
Implementation load detail window

def load_detail_window(self,flag):
        detail_window = detailGUI.DetailWindow(flag,self.current_student_list)
        #Wait for detail_ The window is destroy ed, and then continue to execute the following code
        self.wait_window(detail_window)
        #Refresh information in tree
        self.load_all_student()

add_student(self) function
Click to add students and jump to the details window to add students

    def add_studnet(self):
        flag = 2
        self.current_student_list=[]
        self.load_detail_window(flag)

update_student(self) function
Click a student in the tree + click the modify student button to jump to the detailed window interface to modify the student information, and transfer the clicked student information to the detailed window.

    def update_student(self):
        flag = 3
        try:
            item = self.Tree.selection()[0]
            print(item)
            Temp_student_list = self.Tree.item(item,"values")
            # Traverse to obtain complete student details
            for item in self.all_student_list:
                if item[0] == int(Temp_student_list[0]):
                    self.current_student_list = item
            self.load_detail_window(flag)
        except:
            messagebox.showinfo("System message","Please select the student to be modified on the right!")

view_student(self,event) function
When double clicking a row of data in the tree table, jump to the detailed window interface, and set the control state of the detailed window through flag.

    def view_student(self,event):
        flag = 1
        # Get the data of double clicking a row in the Tree table. If no parameter is specified in selection(), it means that all item s are returned in list form
        # Gets the item identifier for double clicking a row
        item = self.Tree.selection()[0]
        print(item)
        # The data in the Tree table only displays part of the data. In order to display the details form, we need to load the read complete information in the file
        Temp_student_list = self.Tree.item(item,"values") #Through the item method, get all the elements of the changed column and return them in the form of tuples
        print(Temp_student_list)
        print("View details of all students",len(self.all_student_list))
        # Traverse to obtain complete student details
        for item in self.all_student_list:
            if item[0] == int(Temp_student_list[0]):
                self.current_student_list = item
                # print(self.current_student_list)
        
        self.load_detail_window(flag)

delete_student(self) function
Click a row of data in the tree table, and then click the delete student button to delete the data

    def delete_student(self):
        try:
            item = self.Tree.selection()[0]
            Temp_student_list = self.Tree.item(item,"values")
            config={
            "host":"localhost",
            "user":"root",
            "password":"123456",
            "database":"student_manegement"
            }
            db = pymysql.connect(**config)
            cursor = db.cursor()
            sql = "delete from student where student_id=%s"
            cursor.execute(sql,Temp_student_list[0])
            num = messagebox.askokcancel("Tips","Are you sure you want to delete the student:%s Are you?"%Temp_student_list[1])
            if num:
                db.commit()
                messagebox.showinfo("System message","student%s To be deleted!"%Temp_student_list[1])
            else:
                messagebox.showinfo("System message","You canceled deleting students%s"%Temp_student_list[1])
            cursor.close()
            db.close()
            self.load_all_student()
        except:
            messagebox.showinfo("System message","Please select the student to be deleted on the right!")

change_manege(self) function
Click modify password to jump to the modify password window to modify the administrator password

    def change_manege(self):
        update_pwd = change_pwd.Update_pwd(self.current_user,self.current_psw,self.current_state)
        print("main Password and status in the window",self.current_psw,self.current_state)
        self.wait_window(update_pwd)
        print("Modified password:",update_pwd.psw)
        print("Modified status:",update_pwd.state)
        if update_pwd.psw==self.current_psw and update_pwd.state==self.current_state:
            pass
        else:
            messagebox.showinfo("System message","Please login again!")
            self.destroy()
            new_login = login_page.LoginWindow()
            new_login.mainloop()

Student details window


Add student information page display

Modify student information display

View student details display

realization
Create a detailGUI.py module

init(self,flag,current_student) function

# Student form GUI basic layout

from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
import pymysql
import os

class DetailWindow(Toplevel):
    def __init__(self,flag,current_student):
        super().__init__()
        self.title("Student details")
        self.geometry("700x600+600+150")
        self.resizable(0,0) #You cannot change the size of the form
        self.flag = flag  #Receive the flag transmitted from the main window to control the control state of your own window
        self.current_student_list = current_student  #Receive student information from the main window bed
        self.temp_list = []
        # Load control
        self.setup_UI()

load_student_detail(self) function
Show the details of a row of students in the tree clicked from the main window

    def load_student_detail(self):
            if len(self.current_student_list) ==0:
                # messagebox.showinfo("system message", "no data to show!")
                pass
            else:
                self.var_sno.set(self.current_student_list[0]) #Student number
                self.var_name.set(self.current_student_list[1]) #full name
                if "male" in self.current_student_list[2]:  #Gender
                    self.var_gender.set(1)
                else:
                    self.var_gender.set(0)
                self.var_age.set(self.current_student_list[3]) #date of birth
                self.var_id.set(self.current_student_list[4]) #ID
                self.var_mobile.set(self.current_student_list[5]) #Telephone
                self.var_email.set(self.current_student_list[6]) #mailbox
                self.var_home.set(self.current_student_list[7]) #address
                self.var_studyin.set(self.current_student_list[8]) #Admission time
                self.var_academy.set(self.current_student_list[9]) #major
                self.var_link.set(self.current_student_list[10]) #emergency contact 
                self.var_link_phone.set(self.current_student_list[11]) #Emergency contact number

setup_ The UI (self) function implements the interface layout

    def setup_UI(self):
        # detail_UI(self)
        # Set style
        self.Style02 = Style()
        self.Style02.configure("TPanedwindow")
        self.Style02.configure("title.TLabel",font = ("Microsoft YaHei ",10,"bold"))
        self.Style02.configure("TLabel",font = ("Microsoft YaHei ",14,"bold"))
        self.Style02.configure("TButton",font =("Microsoft YaHei ",16,"bold"),foreground = "navy" ,width = 10)  
        self.Style02.configure("TEntry",font=("Microsoft YaHei ",16,"bold"),width = 10)
        self.Style02.configure("large.TEntry",font=("Microsoft YaHei ",16,"bold"),width = 30)
        self.Style02.configure("TRadiobutton",font=("Microsoft YaHei ",14,"bold"))
        

        # Load the banner above
        self.Login_image = PhotoImage(file = "."+os.sep+"images"+os.sep+"shouye.png")
        self.Lable_image = Label(self,image=self.Login_image)  
        self.Lable_image.pack()

        # Add a title
        self.var_title = StringVar()
        self.Label_title = Label(self,text="==Detail form==",style="title.TLabel")
        self.Label_title.place(x=500,y=40)

        # Load a pane
        self.Pane_detail = PanedWindow(self,width=690,height=450,style="TPanedwindow")
        self.Pane_detail.place(x=5,y = 88)

        # Add attribute
        # Row 1: student number
        self.Label_sno = Label(self.Pane_detail,text="Student number:")
        self.Label_sno.place(x=10,y=10)
        self.var_sno = StringVar()
        self.Entry_sno = Entry(self.Pane_detail,textvariable= self.var_sno,style="TEntry")
        self.Entry_sno.place(x=62,y=15)
        # full name
        self.Label_name = Label(self.Pane_detail,text="full name:",style="TLabel")
        self.Label_name.place(x=240,y=10)
        self.var_name = StringVar()
        self.Entry_name = Entry(self.Pane_detail,textvariable=self.var_name,style = "TEntry")
        self.Entry_name.place(x=300,y=15)
        # Gender
        self.Label_gender = Label(self.Pane_detail,text="Gender:").place(x=480,y=10)
        self.var_gender = IntVar()
        self.Radio_man = Radiobutton(self.Pane_detail,text="male",variable=self.var_gender,value = 1,style="TRadiobutton")
        self.Radio_man.place(x=540,y=10)
        self.Radio_woman = Radiobutton(self.Pane_detail,text="female",variable=self.var_gender,value=0,style="TRadiobutton")
        self.Radio_woman.place(x=600,y=10)
        # Row 2: date of birth
        self.Label_age = Label(self.Pane_detail,text="date of birth:",style="TLabel")
        self.Label_age.place(x=10,y=60)
        self.var_age = StringVar()
        self.Entry_age = Entry(self.Pane_detail,textvariable=self.var_age,style="TEntry")
        self.Entry_age.place(x=110,y=65)
        # ID card No.
        self.Label_id = Label(self.Pane_detail,text="ID card No.:",style="TLabel")
        self.Label_id.place(x=280,y=60)
        self.var_id = StringVar()
        self.Entry_id = Entry(self.Pane_detail,textvariable=self.var_id,width =35)
        self.Entry_id.place(x=400,y=65)
        # Row 3: mobile phone number
        self.Label_mobile = Label(self.Pane_detail,text="Telephone number:",style="TLabel")
        self.Label_mobile.place(x=10,y=110)
        self.var_mobile = StringVar()
        self.Entry_mobile = Entry(self.Pane_detail,textvariable=self.var_mobile,style="TEntry")
        self.Entry_mobile.place(x=110,y=115)
        # e-mail address
        self.Label_email = Label(self.Pane_detail,text="e-mail address:",style="TLabel")
        self.Label_email.place(x=280,y=110)
        self.var_email = StringVar()
        self.Entry_email = Entry(self.Pane_detail,textvariable=self.var_email,width =35)
        self.Entry_email.place(x=400,y=115)

        # Row 4: home address
        self.Label_home = Label(self.Pane_detail,text="Home address:",style="TLabel")
        self.Label_home.place(x=10,y=160)
        self.var_home = StringVar()
        self.Entry_home = Entry(self.Pane_detail,textvariable=self.var_home,width=60)
        self.Entry_home.place(x=110,y=165)

        # Row 5: admission time
        self.Label_studyin = Label(self.Pane_detail,text="Admission time:",style = "TLabel")
        self.Label_studyin.place(x=10,y=210)
        self.var_studyin = StringVar()
        self.Entry_studyin = Entry(self.Pane_detail,textvariable=self.var_studyin,style="TEntry")
        self.Entry_studyin.place(x=110,y=215)
        # major
        self.Label_academy = Label(self.Pane_detail,text="major:",style="TLabel")
        self.Label_academy.place(x=320,y=210)
        self.var_academy = StringVar()
        self.Entry_academy = Entry(self.Pane_detail,textvariable=self.var_academy,width = 25)
        self.Entry_academy.place(x=400,y=215)

        # Row 6: emergency contact
        self.Label_link = Label(self.Pane_detail,text="emergency contact :",style="TLabel")
        self.Label_link.place(x=10,y=260)
        self.var_link = StringVar()
        self.Entry_link = Entry(self.Pane_detail,textvariable=self.var_link,style="TEntry")
        self.Entry_link.place(x=140,y=265)
        # Emergency contact number
        self.Label_link_phone = Label(self.Pane_detail,text="Emergency contact telephone:",style="TLabel")
        self.Label_link_phone.place(x=320,y=260)
        self.var_link_phone = StringVar()
        self.Entry_link_phone = Entry(self.Pane_detail,textvariable=self.var_link_phone,style="TEntry")
        self.Entry_link_phone.place(x=500,y=265)

        # Place two buttons
        self.Button_save = Button(self,text="preservation",style="TButton",command=lambda:self.commit())
        self.Button_save.place(x=350,y=550)
        self.Button_exit = Button(self,text="close",style="TButton",command=lambda:self.close_window())
        self.Button_exit.place(x=510,y=550)
        
        #Initialize interface data and control status
        self.load_student_detail()
        self.load_windows_flag()

commit(self) function
Click the Save button to add and modify student information

    def commit(self):
        if self.flag == 1:
            pass
        else :        
            #Add student information
            if self.flag ==2: 
                break_flag=1
                try:
                    while break_flag:
                        self.get_input()
                        if len(self.Entry_sno.get())==0 or len(self.Entry_name.get()) == 0 or len(self.Entry_id.get())==0 or len(self.Entry_mobile.get())==0 or len(self.Entry_studyin.get())==0 or len(self.Entry_academy.get())==0 or len(self.Entry_link.get())==0 or len(self.Entry_link_phone.get())==0:
                            messagebox.showinfo("System message","Student number, name, ID card, telephone number, enrollment time, major, contact and contact telephone cannot be blank!")   
                        else:
                            self.get_input()
                            sql = "insert into student values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
                            self.connect_database(sql,(self.temp_list[0],
                                                    self.temp_list[1],
                                                    self.temp_list[2],
                                                    self.temp_list[3],
                                                    self.temp_list[4],
                                                    self.temp_list[5],
                                                    self.temp_list[6],
                                                    self.temp_list[7],
                                                    self.temp_list[8],
                                                    self.temp_list[9],
                                                    self.temp_list[10],
                                                    self.temp_list[11]))
                            messagebox.showinfo("System message","Student information added successfully")
                            break_flag=messagebox.askyesno("Tips","Continue adding students?")
                            if break_flag:
                                self.Entry_sno.delete(0,"end")
                                self.Entry_name.delete(0,"end")
                                # self.var_gender.delete(0,"end")
                                self.Entry_age.delete(0,"end")
                                self.Entry_id.delete(0,"end")
                                self.Entry_mobile.delete(0,"end")
                                self.Entry_email.delete(0,"end")
                                self.Entry_home.delete(0,"end")
                                self.Entry_studyin.delete(0,"end")
                                self.Entry_academy.delete(0,"end")
                                self.Entry_link.delete(0,"end")
                                self.Entry_link_phone.delete(0,"end")
                    # Destroy this window after saving
                    self.destroy()
                except pymysql.err.OperationalError as e:
                    messagebox.showerror("error",e)
                except pymysql.err.DataError as e:
                    messagebox.showerror("error",e)
                        
                # Modify student information
            elif self.flag == 3:
                self.get_input()
                print(self.temp_list)
                if len(self.Entry_sno.get())==0 or len(self.Entry_name.get()) == 0 or len(self.Entry_id.get())==0 or len(self.Entry_mobile.get())==0 or len(self.Entry_studyin.get())==0 or len(self.Entry_academy.get())==0 or len(self.Entry_link.get())==0 or len(self.Entry_link_phone.get())==0:
                    messagebox.showinfo("System message","Student number, name, ID card, telephone number, enrollment time, major, contact and contact telephone cannot be blank!")
                else:
                    self.get_input()
                    sql = "update student set name=%s,gender=%s,brith_day=%s,ident=%s,mobile=%s,email=%s,home=%s,studyin=%s,academy=%s,link=%s,link_phone=%s  where student_id = %s"
                    self.connect_database(sql,(self.temp_list[1],
                                            self.temp_list[2],
                                            self.temp_list[3],
                                            self.temp_list[4],
                                            self.temp_list[5],
                                            self.temp_list[6],
                                            self.temp_list[7],
                                            self.temp_list[8],
                                            self.temp_list[9],
                                            self.temp_list[10],
                                            self.temp_list[11],
                                            self.temp_list[0]))
                    messagebox.showinfo("System message","Student information modified successfully!")
                    # Destroy this window after saving
                    self.destroy()

*connect_ The database (self, SQL, value) function operates the database

    def connect_database(self,sql,*value):
        config={
                    "host":"localhost",
                    "user":"root",
                    "password":"123456",
                    "database":"student_manegement"
                }
        db = pymysql.connect(**config)
        cursor = db.cursor()
        cursor.execute(sql,*value)
        
        db.commit()
        # self.find_all=cursor.fetchall()
        cursor.close()
        db.close()

get_ The input (self) function gets the data in the input box

   def get_input(self):
        # Get the input box information and save it in the list
        self.temp_list = []
        
        self.temp_list.append(int(self.Entry_sno.get()))
        self.temp_list.append(self.Entry_name.get().strip())
        if self.var_gender.get() == 1:
            self.temp_list.append("male")
        else:
            self.temp_list.append("female")
        self.temp_list.append(self.Entry_age.get().strip())
        self.temp_list.append(self.Entry_id.get().strip())
        self.temp_list.append(self.Entry_mobile.get().strip())
        self.temp_list.append(self.Entry_email.get().strip())
        self.temp_list.append(self.Entry_home.get().strip())
        self.temp_list.append(self.Entry_studyin.get().strip())
        self.temp_list.append(self.Entry_academy.get().strip())
        self.temp_list.append(self.Entry_link.get().strip())
        self.temp_list.append(self.Entry_link_phone.get().strip())

Modify password interface

Display of password modification interface

realization

Create a new change_pwd.py module

from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
import pymysql
import os

class Update_pwd(Toplevel):
    def __init__(self,user,psw,state):
        super().__init__()
        self.title("Change Password")
        self.geometry("500x500+100+80")
        self.resizable(0,0)
        self["bg"]="cornflowerblue"
        self.user = user
        self.current_user=[]
        self.psw = psw
        self.state = state
        self.setup_UI()
        
    def setup_UI(self):
        self.Style03 = Style()
        self.Style03.configure("TPanedwindow",background="white")
        self.Style03.configure("TRadiobutton",font=("Microsoft YaHei ",12,"bold"),background="white")
        self.Style03.configure("TLabel",background="white")
        
        self.Pane_change = Panedwindow(self,width=450,height=450,style="TPanedwindow")
        self.Pane_change.place(x=25,y=25)
        
        self.Lable_username = Label(self.Pane_change,text="user name",width=100,font=("Microsoft YaHei ",14,"bold"),style="TLabel")
        self.Lable_username.place(x=50,y=100)
        self.var_username = StringVar()
        self.var_username.set(self.user)
        self.Entry_username = Entry(self.Pane_change,textvariable=self.var_username,font=("Microsoft YaHei ",14,"bold"))
        self.Entry_username.place(x=115,y=100)
        self.Entry_username["state"] = DISABLED
        
        self.Lable_userpwd_old = Label(self.Pane_change,text="Original password",width=100,font=("Microsoft YaHei ",14,"bold"),style="TLabel")
        self.Lable_userpwd_old.place(x=50,y=150)
        self.var_userpwd_old = StringVar()
        self.Entry_userpwd_old = Entry(self.Pane_change,textvariable=self.var_userpwd_old,font=("Microsoft YaHei ",14,"bold"))
        self.Entry_userpwd_old.place(x=115,y=150)
        
        self.Lable_userpwd = Label(self.Pane_change,text="New password",width=100,font=("Microsoft YaHei ",14,"bold"),style="TLabel")
        self.Lable_userpwd.place(x=50,y=200)
        self.var_userpwd = StringVar()
        self.Entry_userpwd = Entry(self.Pane_change,textvariable=self.var_userpwd,font=("Microsoft YaHei ",14,"bold"))
        self.Entry_userpwd.place(x=115,y=200)
        
        self.Lable_userstate = Label(self.Pane_change,text="state",width=100,font=("Microsoft YaHei ",14,"bold"),style="TLabel")
        self.Lable_userstate.place(x=70,y=250)
        self.var_userstate = StringVar()
        self.Radio_frozen = Radiobutton(self.Pane_change,text="normal",variable=self.var_userstate,value = 1,style="TRadiobutton")
        self.Radio_frozen.place(x=115,y=252)
        self.Radio_disfrozen = Radiobutton(self.Pane_change,text="frozen",variable=self.var_userstate,value=0,style="TRadiobutton")
        self.Radio_disfrozen.place(x=170,y=252)
        
        self.Button_OK = Button(self.Pane_change,text="determine",command=lambda:self.commit())
        self.Button_OK.place(x=80,y=300)
        self.Button_Cancel = Button(self.Pane_change,text="cancel",command=lambda:self.cancel())
        self.Button_Cancel.place(x=220,y=300)
        
        
        
        
    def load_database(self,sql,*value):
        config={
            "host":"localhost",
            "user":"root",
            "password":"123456",
            "database":"student_manegement"
        }
        db = pymysql.connect(**config)
        cursor = db.cursor()
        cursor.execute(sql,*value)
        db.commit()
        self.current_user = cursor.fetchall()
        cursor.close()
        db.close()
        
    def commit(self):
        if len(self.var_userpwd.get())==0 or len(self.var_userpwd_old.get())==0 or len(self.var_userstate.get())==0:
            messagebox.showinfo("system information ","The input box cannot be empty!")
        else:
            manege_list = []
            manege_list.append(self.var_userpwd_old.get())
            manege_list.append(self.var_userpwd.get())
            manege_list.append(self.var_userstate.get())
            print(manege_list)
            
            if manege_list[0]==self.psw:
                
                sql = "select * from manege where user_name=%s"
                self.load_database(sql,self.user)
                sql = "update manege set user_pwd=%s,user_state=%s where user_name=%s"
                self.load_database(sql,(manege_list[1],manege_list[2],self.user))
                messagebox.showinfo("System message","Change succeeded, please login again")
                print("After changing the password:",self.current_user)
                self.psw = manege_list[1]
                self.state=manege_list[2]
                self.destroy()
            else:
                messagebox.showinfo("System message","Original password input error! Please re-enter")
    def cancel(self):
        self.destroy()

Posted by ViN86 on Wed, 17 Nov 2021 04:36:53 -0800