Python 实例:手机通讯录(使用GUI图形界面并用mysql记录数据)

使用数据库远比使用text文本记录数据方便、简单、代码也简洁,少
运行截图:
Python 实例:手机通讯录(使用GUI图形界面并用mysql记录数据)_第1张图片
代码复制粘贴后只要修改一下自己数据库的用户名和密码就可以使用了
Python 实例:手机通讯录(使用GUI图形界面并用mysql记录数据)_第2张图片
贴代码~

import tkinter
import tkinter.messagebox
import pymysql

class MainForm:
    def __init__(self):
        root = tkinter.Tk()# 根窗体
        # 标题名称
        root.title('通讯录')
        # 设置窗体初始大小
        root.geometry("650x550")
        # 设置窗体不可拉升
        root.resizable(width=False, height=False)
        # ---------------设置数据库----------------

        # 连接数据库
        conn = pymysql.connect(
            host='localhost',
            user='root',#数据库用户名
            password='*****',#数据库密码
            port=3306,
            charset='utf8'
        )
        # 获得游标
        cursor = conn.cursor()
        # 创建数据库-phonebook
        sql_creat = "create database if not exists phonebook"
        cursor.execute(sql_creat)
        # 创建数据表-phonebook,并设定相关属性--名字,号码,邮箱,地址
        sql_use = 'use phonebook'
        cursor.execute(sql_use)
        sql_table = 'create table if not exists perinfo(perName varchar(20) primary key,' \
                    'perNumber varchar(10) not null,' \
                    'perEmail varchar(20) not null,' \
                    'perAddress varchar(45) not null )'
        cursor.execute(sql_table)

        # 添加新联系人
        def handler_1(event):
            def newinfo(event):
                name = name_str.get()
                phone = phone_num.get()
                mail = mail_adr.get()
                address = adr_str.get()
                if name == "" or phone == "" or mail == "" or address == "":
                    tkinter.messagebox.showerror('错误', '所填信息不能为空')
                else:
                    # 向数据库插入一条记录 ,字符串和数字的区别:values(%d , '%s')
                    sql = "insert into perinfo(perName, perNumber, perEmail, perAddress) values ('%s','%s','%s','%s')"
                    data = (name, phone, mail, address)
                    # data = ('小张',151, '[email protected]', '南昌')
                    # data = (name_str.get(), phone_num.get(), mail_adr.get(), adr_str.get())
                    cursor.execute(sql % data)
                    conn.commit()
                    # 弹出注册成功消息框
                    tkinter.messagebox.showinfo('消息提示框', f'添加“{name}“为联系人成功!')
                    # 注册成功关闭注册框
                    window_add.destroy()

            # 新建注册界面
            window_add = tkinter.Toplevel(root)
            window_add.geometry('300x300')
            window_add.title('注册')
            # 姓名
            name_str = tkinter.StringVar()
            tkinter.Label(window_add, text='请输入姓  名:').place(x=10, y=10)
            tkinter.Entry(window_add, textvariable=name_str).place(x=110, y=10)
            # 手机号
            phone_num = tkinter.StringVar()
            tkinter.Label(window_add, text='请输入手机号:').place(x=10, y=50)
            tkinter.Entry(window_add, textvariable=phone_num).place(x=110, y=50)
            # 邮箱
            mail_adr = tkinter.StringVar()
            tkinter.Label(window_add, text='请输入邮  箱:').place(x=10, y=90)
            tkinter.Entry(window_add, textvariable=mail_adr).place(x=110, y=90)
            # 地址
            adr_str = tkinter.StringVar()
            tkinter.Label(window_add, text='请输入地  址:').place(x=10, y=130)
            tkinter.Entry(window_add, textvariable=adr_str).place(x=110, y=130)
            # 确认注册按钮及位置
            confirm_button = tkinter.Button(window_add, text='确认添加', font=('黑体', 15, 'bold'))
            confirm_button.bind("", newinfo)
            confirm_button.place(x=100, y=180)

        # 查看所有联系人
        def handler_2(event):
            sql = "select perName, perNumber, perEmail, perAddress from perinfo"
            cursor.execute(sql)
            test = cursor.fetchall()
            print(test)
            if cursor.fetchall() != "()":
                # 窗体设置
                window_all = tkinter.Toplevel(root)
                window_all.geometry('600x400')
                window_all.title('通讯录名单')
                tkinter.Label(window_all, text="通讯录联系人", font=('黑体', 15, 'bold')).grid()
                # 标题
                name_label = tkinter.Label(window_all, text="名字", font=('黑体', 15, 'bold'))
                name_label.grid(row=1, column=0)
                phone_label = tkinter.Label(window_all, text="手机号", font=('黑体', 15, 'bold'))
                phone_label.grid(row=1, column=1)
                mail_label = tkinter.Label(window_all, text="邮箱", font=('黑体', 15, 'bold'))
                mail_label.grid(row=1, column=2)
                address_label = tkinter.Label(window_all, text="地址", font=('黑体', 15, 'bold'))
                address_label.grid(row=1, column=3)
                # 设置每个联系人信息的写入行
                sql = "select perName, perNumber, perEmail, perAddress from perinfo"
                cursor.execute(sql)
                row_count = 1
                for row_info in cursor.fetchall():
                    row_count += 1
                    column_count = 0
                    for column_info in row_info:
                        tktest = tkinter.Label(window_all, text=column_info, font=('黑体', 13, 'bold'))
                        tktest.grid(row=row_count, column=column_count)
                        column_count += 1
            else:
                tkinter.messagebox.showinfo('消息提示框', '通讯录为空')

        # 删除联系人
        def handler_3(event):
            def delinfo(event):
                name = name_str.get()
                if cursor.fetchall() != None:
                    if name != "":
                        sql = "delete from perinfo where pername = '%s'"
                        data = (name)
                        cursor.execute(sql % data)
                        conn.commit()
                        tkinter.messagebox.showinfo('消息提示框', '删除成功!')
                    else:
                        tkinter.messagebox.showinfo('消息提示框', '请输入正确信息')
                else:
                    tkinter.messagebox.showinfo('消息提示框', '通讯录为空!')

            window_del = tkinter.Toplevel(root)
            window_del.geometry('300x300')
            window_del.title('删除联系人')
            # 输入删除的姓名
            name_str = tkinter.StringVar()
            tkinter.Label(window_del, text='请输入要删除的联系人名字:', font=('黑体', 15, 'bold')).place(x=10, y=10)
            tkinter.Entry(window_del, textvariable=name_str).place(x=80, y=60)
            # 确认删除按钮及位置
            confirm_button = tkinter.Button(window_del, text='确认删除', font=('黑体', 15, 'bold'))
            confirm_button.bind("", delinfo)
            confirm_button.place(x=100, y=180)

        # 更新联系人信息
        def handler_4(event):
            def updateinfo(event):
                name_old = name_del.get()
                name = name_new.get()
                phone = phone_new.get()
                mail = mail_new.get()
                address = address_new.get()
                # 如果通讯录.txt文件不为空时,执行下面代码
                if cursor.fetchall() != None:
                    if name != "" and phone != "" and mail != "" and address != "":
                        sql = "update perinfo set perName='%s', perNumber='%s', perEmail= '%s', perAddress= '%s' \
                                         where perName = '%s'"
                        data = (name, phone, mail, address, name_old)
                        cursor.execute(sql % data)
                        conn.commit()
                        tkinter.messagebox.showinfo('消息提示框', '更新成功!')
                    else:
                        tkinter.messagebox.showinfo('消息提示框', '请输入正确信息,或输入完整')
                else:
                    tkinter.messagebox.showinfo('消息提示框', '通讯录为空')

            window_update = tkinter.Toplevel(root)
            window_update.geometry('300x300')
            window_update.title('修改联系人')
            # 输入要更新的联系人姓名
            name_del = tkinter.StringVar()
            tkinter.Label(window_update, text='请输入要修改信息的联系人名字:', font=('黑体', 13, 'bold')).place(x=10, y=10)
            tkinter.Entry(window_update, textvariable=name_del).place(x=80, y=40)
            # 输入要更新的相关信息
            name_new = tkinter.StringVar()
            phone_new = tkinter.StringVar()
            mail_new = tkinter.StringVar()
            address_new = tkinter.StringVar()
            tkinter.Label(window_update, text='请输入修改后的信息:', font=('黑体', 13, 'bold')).place(x=10, y=70)
            # 输入更改后的联系人信息
            tkinter.Label(window_update, text='姓  名:').place(x=20, y=100)
            tkinter.Entry(window_update, textvariable=name_new).place(x=80, y=100)
            tkinter.Label(window_update, text='手机号:').place(x=20, y=130)
            tkinter.Entry(window_update, textvariable=phone_new).place(x=80, y=130)
            tkinter.Label(window_update, text='邮  箱:').place(x=20, y=160)
            tkinter.Entry(window_update, textvariable=mail_new).place(x=80, y=160)
            tkinter.Label(window_update, text='地  址:').place(x=20, y=190)
            tkinter.Entry(window_update, textvariable=address_new).place(x=80, y=190)
            # 确认按钮
            confirm_button = tkinter.Button(window_update, text='确认修改', font=('黑体', 15, 'bold'))
            confirm_button.bind("", updateinfo)
            confirm_button.place(x=100, y=250)

        # 查找---联系人信息
        def handler_5(event):
            def findinfo(event):
                name = name_find.get()
                # 如果数据库不为空则执行以下语句
                if cursor.fetchall() != None:
                    sql = "select perName, perNumber, perEmail, perAddress from perinfo where pername= '%s'"
                    data = (name)
                    cursor.execute(sql % data)
                    # 创建一个frame显示框
                    Frame_info = tkinter.Frame(window_find, height=150, width=180)
                    Frame_info.place(x=20, y=80)
                    # 在Frame中显示联系人的信息
                    tem_text = "姓名:" + '%s' + " " * 50 + '\n' \
                               + "号码:" + '%s' + " " * 50 + '\n' \
                               + "邮箱:" + '%s' + " " * 50 + '\n' \
                               + "地址:" + '%s' + " " * 50 + '\n'
                    tktest = tkinter.Label(Frame_info, text=tem_text % cursor.fetchone(), font=('黑体', 13, 'bold'))
                    tktest.pack(side="top", anchor='w')
                else:
                    tkinter.messagebox.showinfo('消息提示框', '通讯录为空')

            window_find = tkinter.Toplevel(root)
            window_find.geometry('300x300')
            window_find.title('修改联系人')
            # 输入要更新的联系人姓名
            name_find = tkinter.StringVar()
            tkinter.Label(window_find, text='请输入要查询的联系人名字:', font=('黑体', 13, 'bold')).place(x=10, y=10)
            tkinter.Entry(window_find, textvariable=name_find).place(x=80, y=40)
            # 确认按钮
            confirm_button = tkinter.Button(window_find, text='确认查询', font=('黑体', 15, 'bold'))
            confirm_button.bind("", findinfo)
            confirm_button.place(x=100, y=250)

        # 退出
        def handler_6(event):
            root.destroy()


        # --------------------- GUI按钮选项 -------------------------------
        # 添加联系人
        button1 = tkinter.Button(root, text="1.添加联系人", width=20, font=('黑体',15,'bold'))
        button1.place(x=208,y=50)
        button1.bind('', handler_1)

        # 查看通讯录
        button2 = tkinter.Button(root, text="2.查看通讯录", width=20, font=('黑体', 15, 'bold'))
        button2.place(x=208, y=130)
        button2.bind('', handler_2)

        # 删除联系人
        button3 = tkinter.Button(root, text="3.删除联系人", width=20, font=('黑体', 15, 'bold'))
        button3.place(x=208, y=210)
        button3.bind('', handler_3)

        # 修改联系人
        button4 = tkinter.Button(root, text="4.修改联系人", width=20, font=('黑体', 15, 'bold'))
        button4.place(x=208, y=290)
        button4.bind('', handler_4)

        # 查找联系人
        button5 = tkinter.Button(root, text="5.查找联系人", width=20, font=('黑体', 15, 'bold'))
        button5.place(x=208, y=370)
        button5.bind('', handler_5)

        # 退出
        button6 = tkinter.Button(root, text="6.   退出   ", width=20, font=('黑体', 15, 'bold'))
        button6.place(x=208, y=450)
        button6.bind('', handler_6)

        root.mainloop()  # 显示主窗体

def main():#主函数
        MainForm()#实例化窗体类

if __name__=='__main__':#判断程序执行名称
        main()#调用主函数

你可能感兴趣的:(作业,mysql,python,数据库)