import tkinter as tk import pickle import tkinter.messagebox as msgbox window = tk.Tk() window.resizable(0, 0) window.title("修改") # 窗口居中 ww, wh = 400, 250 sw, sh = window.winfo_screenwidth(), window.winfo_screenheight() x, y = (sw - ww) / 2, (sh - wh) / 2 window.geometry("%dx%d+%d+%d" % (ww, wh, x, y)) # 用户名 l_usr = tk.Label(window, text="用户名:") l_usr.place(x=50, y=60) # 密码 l_key = tk.Label(window, text="新密码:") l_key.place(x=50, y=90) # 密码确认 l_cf = tk.Label(window, text="确认密码:") l_cf.place(x=50, y=120) # 单行文本框 读取当前用户的用户名,并显示在文本框中 usr_info = "" with open("record.txt", "r") as fp: usr_info += fp.readlines()[1] var_usr = tk.StringVar() var_usr.set(usr_info) var_key = tk.StringVar() var_cf = tk.StringVar() e_usr = tk.Entry(window, width=35, textvariable=var_usr) e_key = tk.Entry(window, width=35, textvariable=var_key) e_cf = tk.Entry(window, width=35, textvariable=var_cf) e_usr.place(x=120, y=60) e_key.place(x=120, y=90) e_cf.place(x=120, y=120) def check_or_create(yonghu, mima): listAll = [] with open("administrators.pickle", "rb") as file1: try: while True: temp = pickle.load(file1) listAll.append(temp) except EOFError: pass # 读取了空文件的操作 if len(listAll) != 0: for i in range(len(listAll)): if (listAll[i][0] != yonghu) or (listAll[i][1] != mima): listAll.pop(i) listAll.append((yonghu, mima)) temp_file = open("administrators.pickle", "wb") for p in listAll: pickle.dump(p, temp_file) temp_file.close() msgbox.showinfo(message="修改成功") window.quit() break else: msgbox.showerror(message="未修改") # 防止意外删除而报错,默认管理员接管程序 else: with open("administrators.pickle", "wb+") as file4: pickle.dump(("admin", "admin"), file4) # 保存 def save(): # 获取输入信息 usr = var_usr.get() key = var_key.get() cf = var_cf.get() # 先检查用户名输入是否为空,若为空则报错 if usr != "": if key != "": if cf != "": # 先检查两次密码是否一致 if key == cf: # 试图打开文件并读取内容,若文件不存在则新建并初始化 try: check_or_create(usr, key) except FileNotFoundError: with open("administrators.pickle", "wb") as file3: pickle.dump(("admin", "admin"), file3) else: pass else: msgbox.showerror(title="⚠", message="两次密码不一致") else: msgbox.showerror("⚠", "确认密码为空!") else: msgbox.showerror("⚠", "密码为空!") else: msgbox.showerror("⚠", "用户名为空!") # 按钮控件 btn_save = tk.Button(window, text="保存", width=10, command=save) btn_exit = tk.Button(window, text="取消", width=10, command=window.quit) btn_save.place(x=140, y=170) btn_exit.place(x=240, y=170) window.mainloop()