在设计学生管理系统之前,我们需要明确系统的基本需求:
将代码按功能模块进行划分,每个模块负责一个特定的功能。
main.py
: 主程序入口,负责启动应用。LoginPage.py
: 登录页面,验证用户身份。MainPage.py
: 主界面,包括菜单栏和各子功能页面的切换。view.py
: 各功能页面的具体实现。db.py
: 数据持久化,使用JSON文件存储数据。main.py
主程序入口代码
pythonimport tkinter
from LoginPage import *
root = tkinter.Tk()
root.title('小程序')
LoginPage(root)
root.mainloop()
LoginPage.py
登录页面代码
pythonimport tkinter
import tkinter.messagebox
from MainPage import MainPage
class LoginPage(object):
def __init__(self, master=None):
# root 相当于一个本子
self.root = master
# login_frame 相当于一页纸,一个页面
self.login_frame = tkinter.Frame(self.root)
self.login_frame.grid()
# 设置标题
self.root.title('学生信息管理系统')
self.root.geometry('300x180')
self.username = tkinter.StringVar()
self.password = tkinter.StringVar()
self.create_page()
def create_page(self):
tkinter.Label(self.login_frame, width=15).grid(row=0, column=0)
tkinter.Label(self.login_frame, text='账户: ').grid(row=1, column=0)
tkinter.Entry(self.login_frame, textvariable=self.username).grid(row=1, column=1)
tkinter.Label(self.login_frame, text='密码: ').grid(row=2, column=0)
tkinter.Entry(self.login_frame, textvariable=self.password, show='*').grid(row=2, column=1)
tkinter.Button(self.login_frame, text='登录', command=self.check_login).grid(row=3, column=0)
tkinter.Button(self.login_frame, text='退出', command=self.root.quit).grid(row=3, column=1)
# 点击登录 校验参数
def check_login(self):
print('校验登录')
if self.username.get() == 'admin' and self.password.get() == '123456':
print('登录成功')
self.login_frame.destroy()
# 登录成功后,切换到第二个页面
MainPage(self.root)
else:
tkinter.messagebox.showinfo(title='错误', message='账号或密码错误!')
if __name__ == '__main__':
# root 对象 画板
root = tkinter.Tk()
# LoginPage 画纸
LoginPage(root)
root.mainloop()
MainPage.py
主界面代码
pythonimport tkinter
from view import *
class MainPage(object):
def __init__(self, master=None):
self.root = master # 定义内部变量root
self.root.title('学生信息管理系统 v1.0.1')
self.root.geometry('600x400')
self.create_page()
# 创建不同的Frame
self.insert_frame = InsertFrame(self.root)
self.search_frame = QueryFrame(self.root)
self.about_frame = AboutFrame(self.root)
self.delete_frame = DeleteFrame(self.root)
self.modify_frame = ModifyFrame(self.root)
self.insert_frame.pack() # 默认显示数据录入界面
def create_page(self):
menu_bar = tkinter.Menu(self.root)
menu_bar.add_command(label='录入', command=self.show_insert_frame)
menu_bar.add_command(label='查询', command=self.show_search_frame)
menu_bar.add_command(label='删除', command=self.show_delete_frame)
menu_bar.add_command(label='修改', command=self.show_modify_frame)
menu_bar.add_command(label='关于', command=self.show_about_frame)
self.root['menu'] = menu_bar # 设置菜单栏
def show_insert_frame(self):
self.insert_frame.pack()
self.search_frame.forget()
self.delete_frame.forget()
self.modify_frame.forget()
self.about_frame.forget()
def show_search_frame(self):
self.insert_frame.forget()
self.search_frame.pack()
self.delete_frame.forget()
self.modify_frame.forget()
self.about_frame.forget()
def show_delete_frame(self):
self.insert_frame.forget()
self.search_frame.forget()
self.delete_frame.pack()
self.modify_frame.forget()
self.about_frame.forget()
def show_modify_frame(self):
self.insert_frame.forget()
self.search_frame.forget()
self.delete_frame.forget()
self.modify_frame.pack()
self.about_frame.forget()
def show_about_frame(self):
self.insert_frame.forget()
self.search_frame.forget()
self.delete_frame.forget()
self.modify_frame.forget()
self.about_frame.pack()
def __del__(self):
db.save_data()
if __name__ == '__main__':
root = tkinter.Tk()
MainPage(root)
root.mainloop()
view.py
各功能页面实现代码
pythonimport tkinter
from tkinter import ttk
from db import db
class InsertFrame(tkinter.Frame):
def __init__(self, root):
# 继承
super().__init__(master=root)
self.username = tkinter.StringVar()
self.math = tkinter.StringVar()
self.chinese = tkinter.StringVar()
self.english = tkinter.StringVar()
self.status = tkinter.StringVar()
self.create_page()
def create_page(self):
# pad 是 padding 的缩写
tkinter.Label(self, width=15).grid(row=0, column=0, padx=5, pady=5)
tkinter.Label(self, text='姓名: ').grid(row=1, column=0, padx=5, pady=5)
tkinter.Entry(self, textvariable=self.username).grid(row=1, column=1, padx=5, pady=5)
tkinter.Label(self, text='数学: ').grid(row=2, column=0, padx=5, pady=5)
tkinter.Entry(self, textvariable=self.math).grid(row=2, column=1, padx=5, pady=5)
tkinter.Label(self, text='语文: ').grid(row=3, column=0, padx=5, pady=5)
tkinter.Entry(self, textvariable=self.chinese).grid(row=3, column=1, padx=5, pady=5)
tkinter.Label(self, text='英语: ').grid(row=4, column=0, padx=5, pady=5)
tkinter.Entry(self, textvariable=self.english).grid(row=4, column=1, padx=5, pady=5)
tkinter.Button(self, text='录入', command=self.recode).grid(row=5, column=1)
tkinter.Label(self, textvariable=self.status).grid(row=6, column=1)
def recode(self):
stu = {
"name": self.username.get(),
"math": self.math.get(),
"chinese": self.chinese.get(),
"english": self.english.get()
}
db.insert(stu)
print(db.all())
class QueryFrame(tkinter.Frame): # 继承Frame类
def __init__(self, master=None):
super().__init__(master)
self.root = master # 定义内部变量root
self.itemName = tkinter.StringVar()
self.table_frame = tkinter.Frame(self)
self.table_frame.pack()
self.row = 1
self.create_page()
def create_page(self):
self.create_tree_view()
self.show_data_frame()
tkinter.Button(self, text='刷新数据', command=self.show_data_frame).pack(anchor=tkinter.E, pady=5)
def show_data_frame(self):
# 删除原节点
for _ in map(self.tree_view.delete, self.tree_view.get_children("")):
pass
students = db.all()
for index, stu in enumerate(students):
print(stu)
self.tree_view.insert('', index + 1,
values=(stu['name'], str(stu['chinese']), str(stu['math']), str(stu['english'])))
def create_tree_view(self):
# 表格
columns = ("name", "chinese", "math", "english")
self.tree_view = ttk.Treeview(self, show="headings", columns=columns)
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')
self.tree_view.heading('name', text='姓名')
self.tree_view.heading('chinese', text='语文')
self.tree_view.heading('math', text='数学')
self.tree_view.heading('english', text='英语')
self.tree_view.pack(fill=tkinter.BOTH, expand=True)
class DeleteFrame(tkinter.Frame): # 继承Frame类
def __init__(self, master=None):
super().__init__(master)
self.root = master # 定义内部变量root
tkinter.Label(self, text='删除数据').pack()
self.delete_frame = tkinter.Frame(self)
self.delete_frame.pack()
self.status = tkinter.StringVar()
self.v1 = tkinter.StringVar()
self.create_page()
def create_page(self):
tkinter.Label(self.delete_frame, text='根据名字删除信息').pack(anchor=tkinter.W, padx=20)
e1 = tkinter.Entry(self.delete_frame, textvariable=self.v1)
e1.pack(side=tkinter.LEFT, padx=20, pady=5)
tkinter.Button(self.delete_frame, text='删除', command=self._delete).pack()
tkinter.Label(self, textvariable=self.status).pack()
def _delete(self):
name = self.v1.get()
print(name)
r = db.delete_by_name(name)
if r:
self.status.set(f'{name} 已经被删除')
self.v1.set("")
else:
self.status.set(f'{name} 不存在')
class ModifyFrame(tkinter.Frame): # 继承Frame类
def __init__(self, master=None):
super().__init__(master)
self.root = master # 定义内部变量root
tkinter.Label(self, text='修改界面').pack()
self.change_frame = tkinter.Frame(self)
self.change_frame.pack()
self.status = tkinter.StringVar()
self.name = tkinter.StringVar()
self.math = tkinter.StringVar()
self.chinese = tkinter.StringVar()
self.english = tkinter.StringVar()
self.create_page()
def create_page(self):
tkinter.Label(self.change_frame).grid(row=0, stick=tkinter.W, pady=1)
tkinter.Label(self.change_frame, text='姓 名: ').grid(row=1, stick=tkinter.W, pady=10)
tkinter.Entry(self.change_frame, textvariable=self.name).grid(row=1, column=1, stick=tkinter.E)
tkinter.Label(self.change_frame, text='数 学: ').grid(row=2, stick=tkinter.W, pady=10)
tkinter.Entry(self.change_frame, textvariable=self.math).grid(row=2, column=1, stick=tkinter.E)
tkinter.Label(self.change_frame, text='语 文: ').grid(row=3, stick=tkinter.W, pady=10)
tkinter.Entry(self.change_frame, textvariable=self.chinese).grid(row=3, column=1, stick=tkinter.E)
tkinter.Label(self.change_frame, text='英 语: ').grid(row=4, stick=tkinter.W, pady=10)
tkinter.Entry(self.change_frame, textvariable=self.english).grid(row=4, column=1, stick=tkinter.E)
tkinter.Button(self.change_frame, text='查询', command=self._search).grid(row=6, column=0, stick=tkinter.W,
pady=10)
tkinter.Button(self.change_frame, text='修改', command=self._change).grid(row=6, column=1, stick=tkinter.E,
pady=10)
tkinter.Label(self.change_frame, textvariable=self.status).grid(row=7, column=1, stick=tkinter.E, pady=10)
def _search(self):
name = self.name.get()
student = db.search_by_name(name)
if student:
self.math.set(student['math'])
self.chinese.set(student['chinese'])
self.english.set(student['english'])
self.status.set(f'查询到 {name} 同学的信息')
else:
self.status.set(f'没有 {name} 同学的信息')
def _change(self):
name = self.name.get()
math = self.math.get()
chinese = self.chinese.get()
english = self.english.get()
stu = {
'name': name,
'math': math,
'chinese': chinese,
'english': english,
}
r = db.update(stu)
if r:
self.status.set(f'{name} 同学的信息更新完毕')
else:
self.status.set(f'{name} 同学的信息更新失败')
class AboutFrame(tkinter.Frame):
def __init__(self, root):
super().__init__(master=root)
tkinter.Label(self, text='关于页面').pack()
db.py
数据持久化
pythonimport json
class StudentsDB:
"""学生信息管理系统数据模型"""
def __init__(self):
self.students = []
# 加载本地文件中的数据
self._load_students_data()
def insert(self, student):
"""将学生数据插入到列表"""
self.students.append(student)
def all(self):
"""返回所有的学生数据"""
return self.students
def delete_by_name(self, name):
"""根据名字获取学生数据,如果没有就返回 False"""
for student in self.students:
if name == student['name']:
self.students.remove(student)
break
else:
return False
return True
def search_by_name(self, name):
"""根据名字查询学员,没有找到就返回 False"""
for student in self.students:
if name == student['name']:
return student
else:
return False
def update(self, stu):
"""更新学员信息"""
name = stu['name']
for student in self.students:
if name == student['name']:
student.update(stu)
return True
else:
return False
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)
def save_data(self):
"""保存数据到本地文件"""
with open('students.json', mode='w', encoding='utf-8') as f:
text = json.dumps(self.students, ensure_ascii=False)
f.write(text)
db = StudentsDB()
本文作者:柯南
本文链接:
版权声明:©2024 柯南 All rights reserved.