学生信息管理系统-修改学生
代码实现
在上一节中的class StudentManagerApp中添加如下方法:
# 修改学生信息
def modify_student(self):
selection = self.tree.selection()
if not selection:
messagebox.showwarning("警告", "请选择要修改的学员")
return
selected_item = self.tree.item(selection, "values")
id_, name, age, gender = selected_item
# 创建一个新的Toplevel窗口
top = tk.Toplevel(self.root)
top.title("修改学生")
# 设置弹窗在主窗口的中间位置
top.update_idletasks()
width = 300
height = 200
x = (self.root.winfo_width() // 2) - (width // 2) + self.root.winfo_x()
y = (self.root.winfo_height() // 2) - (height // 2) + self.root.winfo_y()
top.geometry(f"{width}x{height}+{x}+{y}")
# 输入框
tk.Label(top, text="姓名:").grid(row=0, column=0, padx=5, pady=5)
tk.Label(top, text="年龄:").grid(row=1, column=0, padx=5, pady=5)
tk.Label(top, text="性别:").grid(row=2, column=0, padx=5, pady=5)
name_var = tk.StringVar(value=name)
age_var = tk.IntVar(value=age)
gender_var = tk.StringVar(value=gender)
tk.Entry(top, textvariable=name_var).grid(row=0, column=1, padx=5, pady=5)
tk.Entry(top, textvariable=age_var, validate="key",
validatecommand=(top.register(self.validate_age), '%P')).grid(row=1, column=1, padx=5, pady=5)
tk.Entry(top, textvariable=gender_var).grid(row=2, column=1, padx=5, pady=5)
# 确定按钮
def ok():
if name_var.get() and age_var.get() and gender_var.get():
new_values = (id_, name_var.get(), age_var.get(), gender_var.get())
self.tree.item(selection, values=new_values)
for i, student in enumerate(self.students):
if student[0] == id_:
self.students[i] = new_values
break
top.destroy() # 关闭对话框
tk.Button(top, text="确定", command=ok).grid(row=3, column=0, columnspan=2, pady=10)
添加方法后,需要在“修改学员”按钮上调用此函数
tk.Button(btn_frame, text="修改学员", command=self.modify_student).pack(side=tk.LEFT, padx=(0, 10))