#创建一个登录界面

import tkinter as tk #设置界面
from tkinter import messagebox #设置提示栏
import pickle #由于读写数据

window=tk.Tk()
window.title("welome")#窗口题目
window.geometry("450x300")#设置大小

canvas=tk.Canvas(window,height=200,width=300)#设置画布大小

image_file=tk.PhotoImage(file="1.gif")#导入图片

image=canvas.create_image(0,0,anchor='nw',image=image_file)#将图片设置到画布中
canvas.pack(side='top')#设置画布在窗口的位置

#分别设置标签var_usr_name 和 var_usr_pwd
tk.Label(window,text="User name").place(x=50,y=150)
tk.Label(window,text="Password").place(x=50,y=190)

#分别设置输入框var_usr_name 和 var_usr_pwd
var_usr_name=tk.StringVar()
var_usr_name.set("python.com")##默认值
entry_usr_name=tk.Entry(window,textvariable=var_usr_name)
entry_usr_name.place(x=160,y=150)

var_usr_pwd=tk.StringVar()
entry_usr_pwd=tk.Entry(window,textvariable=var_usr_pwd,show="*")
entry_usr_pwd.place(x=160,y=190)

#设置登录按钮命令
def usr_login():
# 获取输入框中的值
usr_name=var_usr_name.get()
usr_pwd=var_usr_pwd.get()
try:
with open('user.pickle',"rb") as usr_file:#登录信息存储在'user_pickle'文件中
usr_info=pickle.load(usr_file)
except FileNotFoundError:
with open('user.pickle','wb') as usr_file:
# 设置字典数据类型
usr_info=['admin','admin']
#将数据写入
usr_info=pickle.dump(usr_info,usr_file)

if usr_name in usr_info:
if usr_pwd==usr_info[usr_name]:
messagebox.showinfo("welcom")
else:
messagebox.showerror(title="error",message="you password is error")
else:
is_sign_up=messagebox.askyesno(message="you have not sign up")
if is_sign_up:
usr_sign_up()

# 设置注册界面
def usr_sign_up():
window_sign_up = tk.Toplevel(window) # 创建顶级窗口
window_sign_up.geometry("350x200")
window_sign_up.title("Sign up window ")

# 设置输入变量
new_name = tk.StringVar()
new_password = tk.StringVar()
confirm_password = tk.StringVar()
#设置输入栏
tk.Entry(window_sign_up,textvariable=new_name).place(x=100,y=80)
tk.Entry(window_sign_up,textvariable=new_password).place(x=100,y=120)
tk.Entry(window_sign_up,textvariable=confirm_password).place(x=100,y=150)

tk.Label(window_sign_up,text="name").place(x=50,y=80)
tk.Label(window_sign_up,text="pass").place(x=50,y=120)



def make():
# 获取输入栏数据
nn = new_name.get()
np = new_password.get()
npf = confirm_password.get()

with open('user.pickle', "rb") as usr_file:
exist_sur_info = pickle.load(usr_file)#读取文件信息
if np != npf:
tk.messagebox.showerror(title="Error",message= 'Password and confirm password must make be the same')
elif np in exist_sur_info:
tk.messagebox.showerror(title="Error", message="The user has already sign up")
else:
exist_sur_info[nn] = np
with open('user.pickle', 'wb') as usr_file:
pickle.dump(exist_sur_info, usr_file)
tk.messagebox.showinfo("Welcome")
window_sign_up.destroy()

tk.Button(window_sign_up, text="yes", command=make).pack()


##创建按钮
btn_login=tk.Button(window,text="login",command=usr_login)
btn_login.place(x=170,y=230)
btn_sign_up=tk.Button(window,text="sign_up",command=usr_sign_up)
btn_sign_up.place(x=270,y=230)


window.mainloop()