Python tkinter模块

这个实例是用tkinter写的一个界面,实现了登录注册功能,注册成功会发电子邮件

#导入需要的模块
import tkinter as tk
import tkinter.messagebox
import pymysql
import smtplib
from email.mime.text import MIMEText
import easygui
#创建顶层窗口,Tk()对象
window=tk.Tk()
#设置标题
window.title('Welcome To Baobao\'s Game')
#设置初始窗口大小(宽*高)
window.geometry('480x380')
#禁用窗口最大化按钮
window.resizable(False,False)
#更换默认图标
window.iconbitmap('C:\\Users\\xiaobao\\PycharmProjects\\Ball_Game\\g.ico')
#创建画布,放置图像元素
canvas = tk.Canvas(window, width=480, height=140, bg='green')
#说明图片位置,可用绝对路径,完整的相对路径,导入图片到画布上
image_file = tk.PhotoImage(file='C:\\Users\\xiaobao\\PycharmProjects\\Ball_Game\\ball1.gif')
image = canvas.create_image(0, 0, anchor='nw', image=image_file)
canvas.pack(side='top')
#创建一个label控件,显示文本
label1=tk.Label(window, text='Welcome',font=('Arial', 16),fg='red')
label1.pack()

#用户名,邮箱,密码
label2=tk.Label(window,text='Username:',font=('Arial',14))
label2.place(x=80,y=190)

label4=tk.Label(window,text='E-mail:',font=('Arial',14))
label4.place(x=80,y=230)

label3=tk.Label(window,text='Password:',font=('Arial',14))
label3.place(x=80,y=270)

#用户输入框entry
#用户名
var_usr_name = tk.StringVar()
entry_usr_name = tk.Entry(window,show=None,textvariable=var_usr_name, font=('Arial', 14))
entry_usr_name.place(x=185,y=192)

#邮箱
var_usr_email=tk.StringVar()
entry_usr_email=tk.Entry(window,show=None,textvariable=var_usr_email,font=('Arial',14))
entry_usr_email.place(x=185,y=232)
usr_email=''

#密码
var_usr_pwd=tk.StringVar()
entry_usr_pwd=tk.Entry(window,show='*',textvariable=var_usr_pwd,font=('Arial',14))
entry_usr_pwd.place(x=185,y=272)

#用户登录功能实现
def usr_login(self):
    try:
        #获取用户输入的用户名,邮箱,密码
        usr_name = var_usr_name.get()
        usr_email = var_usr_email.get()
        usr_pwd = var_usr_pwd.get()

        if len(usr_name)<=0 or len(usr_pwd)<=0 or len(usr_email)<=0:
            tk.messagebox.showinfo(title='Error',message='用户名或密码不能为空!')
        else:
            #获取数据库连接对象
            conn = pymysql.connect(host='localhost', port=3306,
                                   database='test183', charset='utf8',
                                   user='root', password='root')
            #通过连接对象获取游标
            cur=conn.cursor()
            sql = """select pwd,email from t_user where username =%s"""
            cur.execute(sql, (usr_name,))
            result = cur.fetchone()
            if result==None:
                is_sign_up = tk.messagebox.askyesno('Welcome! ', 'You have not sign up yet. Sign up now?')
                if is_sign_up:
                    usr_sign_up()
            elif result[0]==usr_pwd and result[1]==usr_email:
                tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name)
            else:
                tk.messagebox.showerror(message='Error, your password or e-mail is wrong, try again.')
    except Exception as e:
        tk.messagebox.showinfo(title='Error!',message=('登陆失败,失败原因为:%s'%e))
    finally:
        conn.close()
        cur.close()
#用户注册
def usr_sign_up():
    window_sign_up = tk.Toplevel(window)
    window_sign_up.geometry('300x230')
    window_sign_up.title('Sign up window')
    window_sign_up.resizable(False, False)

    new_name = tk.StringVar()  # 将输入的注册名赋值给变量
    #new_name.set(var_usr_name)  # 将最初显示定为''
    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=130, y=10)  # entry放置在坐标(150,10).

    new_email=tk.StringVar()
    tk.Label(window_sign_up,text='E-mail:').place(x=10,y=50)
    entry_new_email=tk.Entry(window_sign_up,textvariable=new_email)
    entry_new_email.place(x=130,y=50)

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

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

    def sign_to_Baobao_Website():
        try:
            #获取注册的用户名,密码
            nn = new_name.get()
            np = new_pwd.get()
            npf = new_pwd_confirm.get()
            ne = new_email.get()
            if len(nn)<=0 or len(np)<=0 or len(ne)<=0:
                tk.messagebox.showerror('Error',message='用户名或密码不能为空!')
            elif np != npf:
                tk.messagebox.showerror('Error', 'Password and confirm password must be the same!')
            elif not 8<=len(np)<=16:
                tk.messagebox.showerror('Error',message='请输入8-16位的密码')
            else:
                con = pymysql.connect(host='localhost', port=3306,
                                       database='数据库名', charset='utf8',
                                       user='root', password='数据库密码')
                # 通过连接对象获取游标
                cs1 = con.cursor()
                sql = """select count(*) from t_user where username =%s"""
                cs1.execute(sql, (nn,))
                result = cs1.fetchone()
                if result[0]:
                    tkinter.messagebox.showerror('Error', 'The user has already signed up!')
                else:
                    sql = 'insert into t_user(username,email, pwd) values(%s, %s,%s)'
                    # params = [uname, upwd]
                    result = cs1.execute(sql, (nn, ne,np))
                    con.commit()
                    if result == 1:
                        tkinter.messagebox.showinfo('Welcome', 'You have successfully signed up!')
                        # 用户注册成功即发送欢迎邮件
                        receiver = ne
                        subject = '欢迎来到宝宝的游戏球球大融合'
                        content = '        亲,您好,恭喜您已成功注册宝宝的游戏球球大融合!我们会竭尽全力为您打造极佳的游戏体验,希望您能玩的开心!' \
                                  '当然,如您有什么意见或者建议,我们将非常欢迎您的来信哦!'
                        host = 'smtp.163.com'
                        user_name = '18258685895'
                        pwd = '你的邮箱授权码'
                        sender = 'WXB_0101@163.com'

                        message = MIMEText(content, 'plain', 'utf-8')
                        message['From'] = sender
                        message['to'] = receiver
                        message['Subject'] = subject

                        try:
                            smtp_obj = smtplib.SMTP(host, 25)
                            smtp_obj.login(user_name, pwd)
                            smtp_obj.sendmail(sender, receiver, message.as_string())
                            # easygui.msgbox('邮件发送成功')
                        except smtplib.SMTPException as error:
                            easygui.msgbox('邮件发送失败')
                        #销毁窗口。
                        window_sign_up.destroy()
                    else:
                        tk.messagebox.showinfo(title='Sorry', message='注册失败!')
        except Exception as e:
            tk.messagebox.showinfo(title='Error',message='注册失败,原因是:%s' % e)
        finally:
            cs1.close()
            con.close()
    # 下面的 sign_to_Baobao_Website
    btn_comfirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_Baobao_Website)
    btn_comfirm_sign_up.place(x=180, y=170)

def Print(self):
    pass
    #print(usr_email)

#顶层窗口的登录和注册按钮
btn_login = tk.Button(window, text='Login', width=7,height=1)
btn_login.place(x=140, y=320)
btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up,width=7,height=1)
btn_sign_up.place(x=280, y=320)

#绑定回车键,当密码输完时,按下回车,会自动登录
entry_usr_pwd.bind('<Return>',usr_login)
#绑定鼠标单击事件,单击鼠标时,实现登录
btn_login.bind('<Button-1>',usr_login)
#entry_usr_email.bind('<Return>',Print)
#进入窗口主事件循环
window.mainloop()

下面是注册和登录的效果:

收到的欢迎邮件:

posted @ 2020-06-18 13:52  极限之旅  阅读(674)  评论(0编辑  收藏  举报