Python自学 day04 ---Tkinter GUI视图 简单的登录实现

学习自莫烦Python

由于时间精力有限,就不整理了,在此放一些大佬写好的总结吧~

转载自大佬:aa3214567 --> Python初学——窗口视窗Tkinter

以下是本菜鸟练习的笔记..

# <editor-fold desc="简单的窗口视图">
# #  简单的窗口视图
# import tkinter as tk
#
#
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# e = tk.Entry(window, show='1')                      # 字符显示方式
# e.pack()
#
#
# def insert_point():         # 加到当前指针后面
#     var = e.get()
#     t.insert('insert', var)
#
#
# def insert_end():           # 加到最后
#     var = e.get()
#     # t.insert('end', var)
#     t.insert(2.2, var)       # 加到第二行第三个数
#
#
# b1 = tk.Button(window, text='insert point', width=15, height=2, command=insert_point)
# b1.pack()
# b2 = tk.Button(window, text='insert_end', width=15, height=2, command=insert_end)
# b2.pack()
# t = tk.Text(window, height=2)
# t.pack()
#
# window.mainloop()
# </editor-fold>

# <editor-fold desc="listbox">
# # listbox
# import tkinter as tk
#
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# var1 = tk.StringVar()    # 创建变量
# l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
# l.pack()
#
# def print_selection():
#     value = lb.get(lb.curselection())   # 获取当前选中的文本
#     var1.set(value)     # 为label设置值
#
#
# b1 = tk.Button(window, text='print selection', width=15, height=2, command=print_selection)
# b1.pack()
#
# var2 = tk.StringVar()
# var2.set((11,22,33,44)) # 为变量设置值
#
# # 创建Listbox
#
# lb = tk.Listbox(window, listvariable=var2)  # 将var2的值赋给Listbox
#
# # 创建一个list并将值循环添加到Listbox控件中
# list_items = [1,2,3,4]
# for item in list_items:
#     lb.insert('end', item)  # 从最后一个位置开始加入值
# lb.insert(1, 'first')       # 在第一个位置加入'first'字符
# lb.insert(2, 'second')      # 在第二个位置加入'second'字符
# lb.delete(2)                # 删除第二个位置的字符
# lb.pack()
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="radiobutton 选择按钮">
# radiobutton 选择按钮
# import tkinter as tk
#
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# def print_selection():
#     l.config(text='you have selected ' + var.get())
#
# var = tk.StringVar()
# l = tk.Label(window, bg='yellow', width=20, text='empty')
# l.pack()
#
# r1 = tk.Radiobutton(window, text='Option A',
#                     variable=var, value='A',
#                     command=print_selection)
# # 其中variable=var, value='A'的意思就是,
# # 当我们鼠标选中了其中一个选项,把value的值A放到变量var中,然后赋值给variable
# r2 = tk.Radiobutton(window, text='Option B',
#                     variable=var, value='B',
#                     command=print_selection)
# r3 = tk.Radiobutton(window, text='Option C',
#                     variable=var, value='C',
#                     command=print_selection)
# r1.pack()
# r2.pack()
# r3.pack()
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="Scale 尺度 (滚动条)">
# Scale 尺度
# import tkinter as tk
#
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# # 触发功能
# l = tk.Label(window, bg='yellow', width=20, text='empty')
# l.pack()
#
# def print_selection(v):
#     l.config(text='you have selected ' + v)
# # 创建scale部件
# s = tk.Scale(window, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
#              length=200, showvalue=1, tickinterval=2, resolution=0.01, command=print_selection)
# # orient = tk.HORIZONTAL横向方向
# # showvalue=1 显示当前值 =0 不显示当前值
# # tickinterval=2 步长为2
# s.pack()
#
#
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="Checkbutton 勾选项">
# Checkbutton 勾选项
# import tkinter as tk
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# l = tk.Label(window, bg = 'yellow', width = 20, text = 'empty')
# l.pack()
# def print_selection():
#     if (var1.get() == 1) & (var2.get() == 0):   #如果选中第一个选项,未选中第二个选项
#         l.config(text='I love only Python ')
#     elif (var1.get() == 0) & (var2.get() == 1): #如果选中第二个选项,未选中第一个选项
#         l.config(text='I love only C++')
#     elif (var1.get() == 0) & (var2.get() == 0):  #如果两个选项都未选中
#         l.config(text='I do not love either')
#     else:
#         l.config(text='I love both')             #如果两个选项都选中
#
# var1 = tk.IntVar()
# var2 = tk.IntVar()
# c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0,
#                     command=print_selection)
# # onvalue=1, offvalue=0 选中为1,不选中为0
# c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0,
#                     command=print_selection)
# c1.pack()
# c2.pack()
#
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="Canvas 画布">
# Canvas 画布
# import tkinter as tk
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# # 创建画布
# canvas = tk.Canvas(window, bg='blue', height=100, width=200)
# canvas.pack()
# # 打开图片文件
# image_file = tk.PhotoImage(file='ins.gif')
# image = canvas.create_image(10, 10, anchor='nw', image=image_file)
# # anchor='nw' 铆钉在西北方向(左上角)
#
# # 给定画的多边形的坐标
# x0, y0, x1, y1= 50, 50, 80, 80
# # 画线
# line = canvas.create_line(x0, y0, x1, y1)
#
# oval = canvas.create_oval(x0, y0, x1, y1, fill='red')  #创建一个圆,填充色为`red`红色
# arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180)  #创建一个扇形
# # start=0, extent=180 从0度打开 收到180度
# rect = canvas.create_rectangle(100, 30, 100+20, 30+20)   #创建一个矩形
#
# def moveit():
#     canvas.move(rect, 0, 2)
# # 定义向下移动button
# b = tk.Button(window, text = 'move', command = moveit).pack()
# # command = moveit 不能写成command = moveit() 否则会只执行一次moveit
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="Menubar 菜单">
# import tkinter as tk
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# l = tk.Label(window, text = '', bg = 'yellow')
# l.pack()
#
# # 触发功能
# counter = 0
# def do_job():
#     global counter
#     l.config(text='do '+ str(counter))
#     counter+=1
#
# ##创建一个菜单栏,这里我们可以把他理解成一个容器,在窗口的上方
# menubar = tk.Menu(window)
#
# ##定义一个空菜单单元 tearoff=0能不能被分开
# filemenu = tk.Menu(menubar, tearoff=0)
#
# ##将上面定义的空菜单命名为`File`,放在菜单栏中,就是装入那个容器中
# menubar.add_cascade(label='File', menu=filemenu)
#
# ##在`File`中加入`New`的小菜单,即我们平时看到的下拉菜单,每一个小菜单对应命令操作。
# ##如果点击这些单元, 就会触发`do_job`的功能
# filemenu.add_command(label='New', command=do_job)
# filemenu.add_command(label='Open', command=do_job)##同样的在`File`中加入`Open`小菜单
# filemenu.add_command(label='Save', command=do_job)##同样的在`File`中加入`Save`小菜单
#
# filemenu.add_separator()##这里就是一条分割线
#
# ##同样的在`File`中加入`Exit`小菜单,此处对应命令为`window.quit`
# filemenu.add_command(label='Exit', command=window.quit)
#
# submenu = tk.Menu(filemenu)##和上面定义菜单一样,不过此处实在`File`上创建一个空的菜单
# filemenu.add_cascade(label='Import', menu=submenu, underline=0)##给放入的菜单`submenu`命名为`Import`
# submenu.add_command(label="Submenu1", command=do_job)##这里和上面也一样,在`Import`中加入一个小菜单命令`Submenu1`
#
# window.config(menu = menubar)
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="frame框架 (窗口里的窗口)">
# frame框架 (窗口里的窗口)
# import tkinter as tk
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# ###定义一个`label`显示`on the window`
# tk.Label(window, text='on the window').pack()
#
# ###在`window`上创建一个`frame`
# frm = tk.Frame(window)
# frm.pack()
#
# ###在刚刚创建的`frame`上创建两个`frame`,我们可以把它理解成一个大容器里套了一个小容器,即`frm`上有两个`frame` ,`frm_l`和`frm_r`
#
# frm_l = tk.Frame(frm)
# frm_r = tk.Frame(frm)
#
# ###这里是控制小的`frm`部件在大的`frm`的相对位置,此处`frm_l`就是在`frm`的左边,`frm_r`在`frm`的右边
# frm_l.pack(side='left')
# frm_r.pack(side='right')
#
# ###这里的三个label就是在我们创建的frame上定义的label部件,还是以容器理解,就是容器上贴了标签,来指明这个是什么,解释这个容器。
# tk.Label(frm_l, text='on the frm_l1').pack()##这个`label`长在`frm_l`上,显示为`on the frm_l1`
# tk.Label(frm_l, text='on the frm_l2').pack()##这个`label`长在`frm_l`上,显示为`on the frm_l2`
# tk.Label(frm_r, text='on the frm_r1').pack()##这个`label`长在`frm_r`上,显示为`on the frm_r1`
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="Messagebox 弹窗">
# # messagebox 弹窗
# import tkinter as tk
# from tkinter import messagebox      # 不加这句会出错
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
# def hit_me():
#    tk.messagebox.askquestion(title='Hi', message='hahahaha')
#
# tk.Button(window, text='hit me', command=hit_me).pack()
#
# # tk.messagebox.showinfo(title='',message='')#提示信息对话窗
# # tk.messagebox.showwarning()#提出警告对话窗
# # tk.messagebox.showerror()#提出错误对话窗
# # tk.messagebox.askquestion()#询问选择对话窗
#
# # print(tk.messagebox.askquestion())#返回yes和no
# # print(tk.messagebox.askokcancel())#返回true和false
# # print(tk.messagebox.askyesno())#返回true和false
# # print(tk.messagebox.askretrycancel())#返回true和false
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="pack grid place 放置">
# import tkinter as tk
# window = tk.Tk()
# window.title('my window')
# window.geometry('400x400')
#
#
#
# # pack 放置
# # tk.Label(window, text='1').pack(side='top')#上
# # tk.Label(window, text='1').pack(side='bottom')#下
# # tk.Label(window, text='1').pack(side='left')#左
# # tk.Label(window, text='1').pack(side='right')#右
#
# # grid 方格
# # for i in range(4):
# #     for j in range(3):
# #         tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)
#
# # place
# tk.Label(window, text=2).place(x=20, y=10, anchor='nw')
#
# # 显示主窗口
# window.mainloop()
# </editor-fold>

# <editor-fold desc="登陆窗口">
# 登陆窗口
import tkinter as tk
import pickle
from tkinter import messagebox
window = tk.Tk()
window.title('Welcome to Python')
window.geometry('450x300')

# <editor-fold desc="image">
# welcome image
canvas = tk.Canvas(window, height=200, width=500)#创建画布
image_file = tk.PhotoImage(file='welcome.gif')#加载图片文件
image = canvas.create_image(0,0, anchor='nw', image=image_file)#将图片置于画布上
canvas.pack(side='top')#放置画布(为上端)
# </editor-fold>

# <editor-fold desc="user information">
# user information
tk.Label(window, text='User name: ').place(x=50, y= 150)#创建一个`label`名为`User name: `置于坐标(50,150)
tk.Label(window, text='Password: ').place(x=50, y= 190)

var_usr_name = tk.StringVar()#定义变量
var_usr_name.set('example@python.com')#变量赋值'example@python.com'
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)#创建一个`entry`,显示为变量`var_usr_name`即图中的`example@python.com`
entry_usr_name.place(x=160, y=150)
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')#`show`这个参数将输入的密码变为`***`的形式
entry_usr_pwd.place(x=160, y=190)
# </editor-fold>

def usr_login():
    ##这两行代码就是获取用户输入的`usr_name`和`usr_pwd`
    usr_name = var_usr_name.get()
    usr_pwd = var_usr_pwd.get()

    ##这里设置异常捕获,当我们第一次访问用户信息文件时是不存在的,所以这里设置异常捕获。
    ##中间的两行就是我们的匹配,即程序将输入的信息和文件中的信息匹配。
    try:
        with open('usrs_info.pickle', 'rb') as usr_file:
            usrs_info = pickle.load(usr_file)
    except FileNotFoundError:
        ##这里就是我们在没有读取到`usr_file`的时候,程序会创建一个`usr_file`这个文件,并将管理员
        ##的用户和密码写入,即用户名为`admin`密码为`admin`。
        with open('usrs_info.pickle', 'wb') as usr_file:
            usrs_info = {'admin': 'admin'}
            pickle.dump(usrs_info, usr_file)
    # 如果用户名和密码与文件中的匹配成功,则会登录成功,并跳出弹窗`how are you?`加上你的用户名。
    if usr_name in usrs_info:
        if usr_pwd == usrs_info[usr_name]:
            tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name)
        ##如果用户名匹配成功,而密码输入错误,则会弹出'Error, your password is wrong, try again.'
        else:
            tk.messagebox.showerror(message='Error, your password is wrong, try again.')
    else:  # 如果发现用户名不存在
        is_sign_up = tk.messagebox.askyesno('Welcome',
                                            'You have not sign up yet. Sign up today?')
        # 提示需不需要注册新用户
        if is_sign_up:
            usr_sign_up()
def usr_sign_up():
    def sign_to_Mofan_Python():
        ##以下三行就是获取我们注册时所输入的信息
        np = new_pwd.get()
        npf = new_pwd_confirm.get()
        nn = new_name.get()

        ##这里是打开我们记录数据的文件,将注册信息读出
        with open('usrs_info.pickle', 'rb') as usr_file:
            exist_usr_info = pickle.load(usr_file)

        ##这里就是判断,如果两次密码输入不一致,则提示`'Error', 'Password and confirm password must be the same!'`
        if np != npf:
            tk.messagebox.showerror('Error', 'Password and confirm password must be the same!')

        ##如果用户名已经在我们的数据文件中,则提示`'Error', 'The user has already signed up!'`
        elif nn in exist_usr_info:
            tk.messagebox.showerror('Error', 'The user has already signed up!')

        ##最后如果输入无以上错误,则将注册输入的信息记录到文件当中,并提示注册成功`'Welcome', 'You have successfully signed up!'`
        ##然后销毁窗口。
        else:
            exist_usr_info[nn] = np
            with open('usrs_info.pickle', 'wb') as usr_file:
                pickle.dump(exist_usr_info, usr_file)
            tk.messagebox.showinfo('Welcome', 'You have successfully signed up!')
            ##然后销毁窗口。
            window_sign_up.destroy()


    window_sign_up = tk.Toplevel(window)
    window_sign_up.geometry('350x200')
    window_sign_up.title('Sign up window')

    new_name = tk.StringVar()  # 将输入的注册名赋值给变量
    new_name.set('example@python.com')  # 将最初显示定为'example@python.com'
    tk.Label(window_sign_up, text='User name: ').place(x=10, y=10)  # 将`User name:`放置在坐标(10,10)。
    entry_new_name = tk.Entry(window_sign_up, textvariable=new_name)  # 创建一个注册名的`entry`,变量为`new_name`
    entry_new_name.place(x=150, y=10)  # `entry`放置在坐标(150,10).

    new_pwd = tk.StringVar()
    tk.Label(window_sign_up, text='Password: ').place(x=10, y=50)
    entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*')
    entry_usr_pwd.place(x=150, y=50)

    new_pwd_confirm = tk.StringVar()
    tk.Label(window_sign_up, text='Confirm password: ').place(x=10, y=90)
    entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*')
    entry_usr_pwd_confirm.place(x=150, y=90)

    # 下面的 sign_to_Mofan_Python 我们再后面接着说
    btn_comfirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_Mofan_Python)
    btn_comfirm_sign_up.place(x=150, y=130)

# <editor-fold desc="login and sign up button">
# login and sign up button
btn_login = tk.Button(window, text='Login', command=usr_login)#定义一个`button`按钮,名为`Login`,触发命令为`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)
# </editor-fold>

# 显示主窗口
window.mainloop()
# </editor-fold>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值