order said
Code parsing
One 、 The login page
Two 、 The main page displays
3、 ... and 、 Page shows
Four 、 Query data
5、 ... and 、 Delete data
6、 ... and 、 Modifying data
7、 ... and 、 About the part
8、 ... and 、 Save the data , Save information
order saidHello, brothers , Long time no see ! I'm really busy these days , So once again broke up again ~
My cousin is about to graduate from college , Studied for a semester Python I can't even write a student management system , It really humiliates me , Teach him and refuse to learn , And let me write directly to him , I really want to slap my hands , Finally I wrote it to him , Who makes him my cousin , I still have to help him at the critical moment !
After writing, I put it there , So let's share it with you today !
Don't talk much , Let's go straight ahead !
Code parsing One 、 The login page1、 Define login classes and initialization objects
First, import the modules we need
from main import MainPage
The login page
Bind the palette to the instance object
self.root = master
self.page Drawing paper Show a rectangular area on the screen , It's mostly used as a container .
self.page = tk.Frame(self.root)self.page.pack()self.root.geometry("300x180")
tkinter Variable variables provided , Define user name and password .
self.username = tk.StringVar()self.password = tk.StringVar()
Create a label
Grid layout
tk.Label(self.page).grid(row=0, column=0)# textvariable This parameter is set to tkinter Inside the string variable and Space bound tk.Label(self.page, text=" Account ").grid(row=1, column=0, stick=tk.E, pady=10)tk.Entry(self.page, textvariable=self.username).grid(row=1, column=1, stick=tk.W, pady=10)tk.Label(self.page, text=" password ").grid(row=2, column=0, stick=tk.E, pady=10)tk.Entry(self.page, textvariable=self.password).grid(row=2, column=1, stick=tk.W, pady=10)
command Accept a function Execute login logic
tk.Button(self.page, text=" Sign in ", command=self.login_check).grid(row=3, column=0, stick=tk.W, pady=10)tk.Button(self.page, text=" sign out ", command=root.quit).grid(row=3, column=1, stick=tk.E, pady=10)
2、 Login function
Verify login
Get the account code
name = self.username.get()pwd = self.password.get()
Don't query the database
print(name, pwd)if name == 'admin' and pwd == '123456': tkinter.messagebox.showinfo(title=' Congratulations ', message=' Login successful !')
Destroy the content drawn on the current page
self.page.destroy()
Destroy the contents drawn on the whole page
self.root.destroy()
Page switching
MainPage(self.root)else: tkinter.messagebox.showinfo(title=' error ', message=' Wrong account or password ')
3、 Window call
Call this file method , Run two inputs in this file , The data before the method is called and executed outside .
Create an object , Window object , display .
if __name__ == '__main__': root = tk.Tk() LoginPage(root) root.mainloop()
Two 、 The main page displays 1、 Define page classes , Convenient to call .
Login screen
def __init__(self, master): self.root = master self.page = tk.Frame(self.root) self.page.pack() self.root.geometry("%dx%d" % (600, 400)) self.create_page()
Create a top-level menu , Show menu .
def create_page(self): menubar = tk.Menu(self.root) menubar.add_command(label=" entry ") menubar.add_command(label=" Inquire about ") menubar.add_command(label=" Delete ") menubar.add_command(label=" modify ") menubar.add_command(label=" About ")
3、 ... and 、 Page shows 1、 Bind each page
Too much code written together , More data , It's easy to write wrong , confusion , You can write a file to hold data view.py
stay view.py The file defines the classes of each module
entry
class InputFrame(tk.Frame): # Inherit Frame class def __init__(self, master): # Re parent super().__init__(master) pass
Inquire about
class QueryFrame(tk.Frame): # Inherit Frame class def __init__(self, master=None): super().__init__(master) pass
Delete
class DeleteFrame(tk.Frame): # Inherit Frame class def __init__(self, master=None): super().__init__(master)
modify
class ChangeFrame(tk.Frame): # Inherit Frame class def __init__(self, master=None): super().__init__(master)
About
class AboutFrame(tk.Frame): # Inherit Frame class def __init__(self, master=None): tk.Frame.__init__(self, master) self.root = master
And then in main.py Bind the data in the file
self.input_page = InputFrame(self.root)self.change_page = ChangeFrame(self.root)self.query_page = QueryFrame(self.root)self.delete_page = DeleteFrame(self.root)self.about_page = AboutFrame(self.root)
2、 entry
stay view.py In file InputFrame Class , Name and grades .
x = IntVar(): Integer variables , The default is 0
x = DoubleVar(): Floating point variables , The default is 0.0
x = StringVar(): String variable , The default is ""
x = BooleanVar(): Boolean variables ,True yes 1,False yes 0
self.root = master # Define internal variables rootself.name = tk.StringVar()self.math = tk.StringVar()self.chinese = tk.StringVar()self.english = tk.StringVar()# entry self.status = tk.StringVar()# call create_page() function self.create_page()
To write create_page() function
def create_page(self): # pass # stick Control object orientation tk.W Western bit # pady padding y Width up and down # row That's ok Table layout tk.Label(self).grid(row=0, stick=tk.W, pady=10) tk.Label(self, text=' surname name : ').grid(row=1, stick=tk.W, pady=10) # text variable Bind the data content in the control tk.Entry(self, textvariable=self.name).grid(row=1, column=1, stick=tk.E) tk.Label(self, text=' Count learn : ').grid(row=2, stick=tk.W, pady=10) tk.Entry(self, textvariable=self.math).grid(row=2, column=1, stick=tk.E) tk.Label(self, text=' language writing : ').grid(row=3, stick=tk.W, pady=10) tk.Entry(self, textvariable=self.chinese).grid(row=3, column=1, stick=tk.E) tk.Label(self, text=' Britain language : ').grid(row=4, stick=tk.W, pady=10) tk.Entry(self, textvariable=self.english).grid(row=4, column=1, stick=tk.E) tk.Button(self, text=' entry ', command=self.recode_student).grid(row=5, column=1, stick=tk.E, pady=10) tk.Label(self, textvariable=self.status).grid(row=6, column=1, stick=tk.E, pady=10)
stay main.py Bind these data in
menubar.add_command(label=" entry ", command=self.show_input)
def show_input(self): self.input_page.pack() # pack_forget() Hide layout # self.change_page.pack_forget() # self.query_page.pack_forget() # self.delete_page.pack_forget() # self.about_page.pack_forget()
stay view.py Data entry in the document
def recode_student(self): stu = {'name': self.name.get(), 'chinese': self.chinese.get(), 'math': self.math.get(), 'english': self.english.get()} # You need to refresh the page after clicking and entering self.name.set('') self.chinese.set('') self.math.set('') self.english.set('') db.insert(stu) self.status.set(' Data submitted successfully ') print(stu)
Insert data and save data , Can write a file to save , Too much code to write together , The probability of error is also one db.py file .
class StudentsDB: def __init__(self): self.students = [] def insert(self, student): self.students.append(student)db = StudentsDB()if __name__ == '__main__': print(db.students)
Four 、 Query data stay QueryFrame() Class to add data
ttk.Treeview Tree view , use Baidu Search
shows:
headings
tree
data_list
columns
The value is a list . Each element in the list represents the name of a column identifier . The length of the list is the length of the column .
Inherit Frame class
class QueryFrame(tk.Frame): def __init__(self, master=None): super().__init__(master)
Define internal variables root
self.root = master #columns = ('name', 'chinese', 'math', 'english')self.tree_view = ttk.Treeview(self, show='headings', columns=columns)
Each data size is one grid
self.tree_view.column('name', width=80, anchor='center')self.tree_view.column('chinese', width=80, anchor='center')self.tree_view.column('math', width=80, anchor='center')self.tree_view.column('english', width=80, anchor='center')
The above label and headings
self.tree_view.heading('name', text=' full name ')self.tree_view.heading('chinese', text=' Chinese language and literature ')self.tree_view.heading('math', text=' mathematics ')self.tree_view.heading('english', text=' English ')self.tree_view.pack(fill=tk.BOTH, expand=True)tk.Button(self, text=' The refresh data ', command=self.show_data_frame).pack(anchor=tk.E, pady=5)self.show_data_frame()
The refresh data , Display the data .
def show_data_frame(self): # Delete old stage for _ in map(self.tree_view.delete, self.tree_view.get_children('')): pass # First show all the data stay db Add the display data code to the file students = db.all() index = 0 for stu in students: # print(stu) self.tree_view.insert('', index + 1, values=( stu['name'], stu['chinese'], stu['math'], stu['english'], ))
Display the data
stay db.py To add
def all(self): return self.students
view.py
Refresh insert data
The first parameter :parent : For those with tree Columns Treeview,parent Is the parent node , For the list column only Treeview,parent It is generally empty .
The second parameter :index : Insertion position . It can be END or ’end’ , It can also be digital , If you want to insert new item( Record ) Become the first of a node ,index Set it to 0, And so on .
values: Displayed values and inserted data , This column of data .
self.tree_view.insert('', index + 1, values=( stu['name'], stu['chinese'], stu['math'], stu['english'], ))
Update page after inserting data refresh
map(func, lst), The function variable passed in func Effect to lst In each element of the variable , And make a new list of the results (Python2)/ iterator (Python3) return .
get_children(item=None)
Return to one item All son item, This one item It's a list , If item It's not specified , Returns the of the root directory item
for _ in map(self.tree_view.delete, self.tree_view.get_children('')): pass
stay main.py File binding data
menubar.add_command(label=" Inquire about ", command=self.show_all)def show_all(self): # Hide layout self.input_page.pack_forget() # self.change_page.pack_forget() self.query_page.pack() # self.delete_page.pack_forget() # self.about_page.pack_forget()
5、 ... and 、 Delete data stay DeleteFrame() Class to add data
class DeleteFrame(tk.Frame): # Inherit Frame class def __init__(self, master=None): super().__init__(master) self.root = master # Define internal variables root tk.Label(self, text=' Delete data ').pack() self.delete_frame = tk.Frame(self) self.delete_frame.pack() self.status = tk.StringVar() self.username = tk.StringVar() tk.Label(self.delete_frame, text=' Delete information by name ').pack(anchor=tk.W, padx=20) tk.Entry(self.delete_frame, textvariable=self.username).pack(side=tk.LEFT, padx=20, pady=5) tk.Button(self.delete_frame, text=' Delete ', command=self._delete).pack() tk.Label(self, textvariable=self.status).pack()
1、 Click delete , Delete data
def _delete(self): username = self.username.get() flag, message = db.delete_by_name(username) self.status.set(message)
stay db.py Add delete logic to the file
def delete_by_name(self, name): for student in self.students: if name == student['name']: self.students.remove(student) return True, f'{name} Delete successful ' return False, f'{name} non-existent '
stay main.py Binding data in
menubar.add_command(label=" Delete ", command=self.show_delete)def show_delete(self): self.input_page.pack_forget() self.query_page.pack_forget() self.delete_page.pack()
6、 ... and 、 Modifying data stay ChangeFrame() Class to add data
self.root = master # Define internal variables root tk.Label(self, text=' Modify the interface ').pack() self.change_frame = tk.Frame(self) self.change_frame.pack() self.status = tk.StringVar() self.name = tk.StringVar() self.math = tk.StringVar() self.chinese = tk.StringVar() self.english = tk.StringVar() tk.Label(self.change_frame).grid(row=0, stick=tk.W, pady=1) tk.Label(self.change_frame, text=' surname name : ').grid(row=1, stick=tk.W, pady=10) tk.Entry(self.change_frame, textvariable=self.name).grid(row=1, column=1, stick=tk.E) tk.Label(self.change_frame, text=' Count learn : ').grid(row=2, stick=tk.W, pady=10) tk.Entry(self.change_frame, textvariable=self.math).grid(row=2, column=1, stick=tk.E) tk.Label(self.change_frame, text=' language writing : ').grid(row=3, stick=tk.W, pady=10) tk.Entry(self.change_frame, textvariable=self.chinese).grid(row=3, column=1, stick=tk.E) tk.Label(self.change_frame, text=' Britain language : ').grid(row=4, stick=tk.W, pady=10) tk.Entry(self.change_frame, textvariable=self.english).grid(row=4, column=1, stick=tk.E) tk.Button(self.change_frame, text=' Inquire about ', command=self._search).grid(row=6, column=0, stick=tk.W, pady=10) tk.Button(self.change_frame, text=' modify ', command=self._change).grid(row=6, column=1, stick=tk.E, pady=10) tk.Label(self.change_frame, textvariable=self.status).grid(row=7, column=1, stick=tk.E, pady=10)
1、 Query data
db.py Query data logic in file
def search_by_name(self, name): for student in self.students: if name == student['name']: return True, student return False, f'{name} non-existent '
view.py Click to query the file , Display the data
def _search(self): flag, info = db.search_by_name(self.name.get()) if flag: self.name.set(info['name']) self.chinese.set(info['chinese']) self.math.set(info['math']) self.english.set(info['english']) self.status.set(' Data query successful ') else: # Return the error information directly self.status.set(info)
2、 Modify data and update
db.py File update data logic
def update(self, stu): name = stu['name'] for student in self.students: if name == student['name']: student.update(stu) return True, f'{stu["name"]} User data modified successfully ' else: return False, f'{name} non-existent '
view.py File modification data
def _change(self): stu = {'name': self.name.get(), 'chinese': self.chinese.get(), 'math': self.math.get(), 'english': self.english.get(), } self.name.set('') self.chinese.set('') self.math.set('') self.english.set('') db.update(stu) self.status.set(' Data modified successfully ')
main.py File binding
menubar.add_command(label=" modify ", command=self.show_change)def show_change(self): self.input_page.pack_forget() self.query_page.pack_forget() self.delete_page.pack_forget() self.change_page.pack()
7、 ... and 、 About the part view.py In the AboutFrame() Add data
class AboutFrame(tk.Frame): # Inherit Frame class def __init__(self, master=None): tk.Frame.__init__(self, master) self.root = master # Define internal variables root tk.Label(self, text=' About the work : This work is written by Hey, learn programming Make ').pack(anchor=tk.W) tk.Label(self, text=' About author : Hey, learn programming ').pack(anchor=tk.W) tk.Label(self, text=' copyright : Hey, learn programming ').pack(anchor=tk.W)
main.py Data binding
menubar.add_command(label=" About ", command=self.show_about)def show_about(self): self.input_page.pack_forget() self.query_page.pack_forget() self.delete_page.pack_forget() self.change_page.pack_forget() self.about_page.pack()
8、 ... and 、 Save the data , Save information db.py Save the data
Create an empty json file
import osfile = "students.json"# Judge whether the file exists , Create if it does not exist if not os.path.exists(file): open(file, 'w') # Report errors # os.mknod(file)
Windows Upper Python I won't support it mknod function , Because in Windows Not on node The concept .
1、 Save the data
def save_data(self): with open('students.json', mode='w', encoding='utf-8') as f: text = json.dumps(self.students, indent=2, ensure_ascii=False) f.write(text)
2 、 Reading data
def _load_students_data(self): with open('students.json', mode='r', encoding='utf-8') as f: text = f.read() if text: self.students = json.loads(text)
stay view.py File to call the save function , Save the completed data .
entry
def recode_student(self): db.save_data()
Delete
def _delete(self): db.save_data()
modify
def _change(self): db.save_data()
That's all Python Realization GUI Student management system example code details , More about Python GUI For information about student management system, please pay attention to other relevant articles on software development network !
It feels a little less fun not