python小项目--信息管理系统---新手实践

一,功能简介

除最基本的增,删,改,查,多加了一个导出为excel表格的功能。比较适合刚学完python练习基本语言用。代码中大部分都是使用基本语法来处理数据。
python小项目--信息管理系统---新手实践_第1张图片
新建和查看
python小项目--信息管理系统---新手实践_第2张图片

python小项目--信息管理系统---新手实践_第3张图片
搜索时,界面确实不怎么美观,家庭住址这一栏也直接到了下一行,时间原因,也懒得修改了。
python小项目--信息管理系统---新手实践_第4张图片
修改:
先选择要修改的信息
python小项目--信息管理系统---新手实践_第5张图片
改动:
python小项目--信息管理系统---新手实践_第6张图片
信息覆盖:
python小项目--信息管理系统---新手实践_第7张图片
删除和修改的界面几乎一样一个多选的对话框,这里不展示了。
导出表格:其中C:/Users/acer/Desktop/信息.xlsx为默认路径,选择导出功能时会自动填入
python小项目--信息管理系统---新手实践_第8张图片

python小项目--信息管理系统---新手实践_第9张图片

二,代码

个人小白,python学的比较浅,GUI也是用的自带模块easygui
运行时会生成名为employee_date.json的文件来存储信息
main.py:

import easygui
import function as fun
while True:
    main_menu = easygui.buttonbox('\t\t\t\t菜单界面', title='信息管理系统',
                                  choices=['新建信息', '查看所有信息',
                                           '搜索信息', '修改信息', '删除信息',
                                           '导出为excel表格'])
    if main_menu == '新建信息':
        try:
            fun.new_employee()
        except FileNotFoundError:
            fun.new_filename()
    elif main_menu == '查看所有信息':
        try:
            fun.data_all()
        except FileNotFoundError:
            fun.tip_not_found_file()
    elif main_menu == '修改信息':
        try:
            fun.modify_employee()
        except FileNotFoundError:
            fun.tip_not_found_file()
    elif main_menu == '删除信息':
        try:
            fun.del_data()
        except ValueError:
            fun.del_data2()
        except FileNotFoundError:
            fun.tip_not_found_file()
    elif main_menu == '搜索信息':
        try:
            fun.search_data()
        except FileNotFoundError:
            fun.tip_not_found_file()
    elif main_menu == '导出为excel表格':
        try:
            fun.export_to_excel()
        except FileNotFoundError:
            fun.tip_not_found_file()
    elif main_menu == None:
        break

function.py:

import json
import openpyxl
import easygui
import os
list_employee = []
filename = 'employee_date.json'


def new_filename():
    employee = new_tools1()
    if employee == None:
        return
    tem_list = []
    tem_list.append(employee)
    with open(filename, 'w') as f:
        json.dump(tem_list, f, indent=4)
        f.close()
    easygui.msgbox(msg='Add success', title='tip', ok_button='返回')


def new_employee():
    with open(filename) as f:
        list_employee = json.load(f)
        f.close()
    employee = new_tools1()
    if employee == None:
        return
    with open(filename) as f:
        list_employee = json.load(f)
        list_employee.append(employee)
        f.close()
    with open(filename, 'w') as f:
        json.dump(list_employee, f, indent=4)
        f.close()
    easygui.msgbox(msg='Add success', title='tip', ok_button='返回')


def new_tools1():
    menu1 = easygui.multenterbox('新建信息', '新建信息功能',
                                 ['姓名', '性别(男/女)', '联系方式', '家庭住址'])
    if menu1 == None:
        return menu1
    while len(menu1[1]) != 1 or len(menu1[2]) != 11 or not menu1[2].isdigit():
        menu1 = easygui.multenterbox('格式有误!重新输入', '新建信息功能',
                                     ['姓名', '性别(男/女)', '联系方式', '家庭住址'])
        if menu1 == None:
            return menu1
    employee = {
     
        'name': menu1[0],
        'gender': menu1[1],
        'phone': menu1[2],
        'address': menu1[3]
    }
    return employee


def data_all(w=True):
    with open(filename) as f:
        data = json.load(f)
        f.close()
    if len(data) == 0:
        easygui.msgbox('NOT FOUND MESSAGES!')
        return 1
    value = ['姓名', '性别', '联系方式', '家庭住址']
    i = 0
    while i < len(data):
        for v in data[i].values():
            value.append(v)
        i = i+1
    val_p = ''
    for a in range(len(value)):
        val_p += str(value[a])+'\t\t'
        if a % 4 == 3:
            val_p += '\n'
    if w == False:
        return val_p
    easygui.msgbox(val_p, title='全部信息')


def export_to_excel():
    # 定义要写入的行和列的值
    with open(filename) as f:
        list_employee = json.load(f)
            # 定义excel的sheet_name  "xlsx格式测试表 "
        f.close()
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet_name = "xlsx格式表"
    sheet.title = sheet_name
    path = 'C:/Users/acer/Desktop/信息.xlsx'
    path = easygui.enterbox('导出路径', title='选择路径', default=path)
    if path == None:
        return
    temporary_val_k = ['姓名', '性别', '联系方式', '家庭住址']
    for a in range(0, len(temporary_val_k)):
        sheet.cell(row=1, column=a+1, value=temporary_val_k[a])     #打印表头
    i = 0
    while i < len(list_employee):    #0~len(list)   i:0~4
        temporary_val = []
        for val in list_employee[i].values():     #list_employee is a list ,每个值为字典
            temporary_val.append(val)   #此时temporary_val 是列表,有四个值
        for j in range(len(temporary_val)):
            sheet.cell(i+2, j+1, temporary_val[j])
        i = i+1
    workbook.save(path)
    easygui.msgbox(msg='导出成功', title='tip')


def search_data():
    val_p = data_all(w=False)
    if val_p == 1:
        return
    find_data = easygui.enterbox(val_p,
                                 title='信息搜索')
    if find_data == None:
        return
    with open(filename) as f:
        list_employee = json.load(f)
        f.close()
    value = ['姓名', '性别', '联系方式', '家庭住址']
    i = len(value)
    s = ''
    for category in ['name', 'gender', 'phone', 'address']:
        for dict_employee in list_employee:
            if find_data in dict_employee[category]:
                for element in dict_employee.values():
                    value.append(element)
    if len(value) == 4:
        value.append('NOT FOUND!!')
    for a in range(len(value)):
        s += value[a]+'\t\t'
        if a%i == 3:
            s += '\n'
    easygui.msgbox(msg=s, title='信息检索', ok_button='返回')


def del_data():
    tem = del_mod(m='选择要删除的信息', t='选择删除信息')
    if tem == None:
        return
    for t in range(len(tem)):
        num = ''.join([x for x in tem[t] if x.isdigit()])
        with open(filename) as f:
            list_employee = json.load(f)
            for employee in list_employee:
                if employee['phone'] == num:
                    list_employee.remove(employee)
            f.close()
        with open(filename, 'w') as f:
            json.dump(list_employee, f, indent=4)
            f.close()
    message = '成功删除:\n'
    for a in range(len(tem)):
        message += tem[a]+'\n'
    easygui.msgbox(message, title='tip')


def del_data2():    #解决只有一个信息时的删除错误
    with open(filename) as f:
        list_employee = json.load(f)
        f.close()
    a = '成功删除:\n'
    for a_p in list_employee[0].values():
        a += a_p
    os.remove(filename)
    easygui.msgbox(a, title='tip')


def modify_employee():
    with open(filename) as f:
        list_employee = json.load(f)
        f.close()
    list_tem = []
    value = ['姓名', '性别', '联系方式', '家庭住址']
    tem = del_mod(m='选择要修改的信息', t='修改信息')  #tem is a list
    if tem == None:
        return
    for d in tem:
        for n in range(len(d)):
            t = d[n]
            if t == '男' or t == '女':    #别问为什么要用中间变量t,直接用d[n]不是更简单吗?直接用d[n]不行,不是预期结果
                list_tem.append(d[:n].strip())
                list_tem.append(d[n])
                list_tem.append(d[n+3:n+14])
                list_tem.append(d[n+14:].strip())
    num_list = get_subscript(list_tem)     #若选择要修改的人员信息有两个,此时list_tem == 8,num_list存储要修改信息的下标
    list_tem_a = []
    record = 0
    for a in range(len(list_tem)):  #run twice
        list_tem_a.append(list_tem[a])  #给list_tem_a添加list_tem,当加入四个时说明为一个人的信息
        if a % len(value) == len(value)-1:  #if a%4 == 3
            ret = easygui.multenterbox('', '信息修改', value, list_tem_a)
            if ret == None:
                return
            while len(ret[1]) != 1 or len(ret[2]) != 11 or not ret[2].isdigit():
                ret = easygui.multenterbox('格式有误', '信息修改', value, list_tem_a)   #ret 返回修改过的信息
                if ret == None:
                    return
            list_employee[num_list[record]]['name'] = ret[0]
            list_employee[num_list[record]]['gender'] = ret[1]
            list_employee[num_list[record]]['phone'] = ret[2]
            list_employee[num_list[record]]['address'] = ret[3]
            record = record + 1
            list_tem_a = []
    with open(filename, 'w') as f:
        json.dump(list_employee, f, indent=4)
        f.close()
    easygui.msgbox('修改成功', title='tip')


def get_subscript(list_tem):
    num_list = []
    with open(filename) as f:
        list_employee = json.load(f)
        f.close()
    for n in range(len(list_tem)):
        if n%4 == 2:
            #list_tem[n] == phone
            for num in range(len(list_employee)):
                if list_employee[num]['phone'] == list_tem[n]:
                    num_list.append(num)
    return num_list


def del_mod(m, t):
    i = 0
    s = ''
    val_p = []
    value = []
    with open(filename) as f:
        data = json.load(f)
        f.close()
    a = data
    if len(data) == 0:
        easygui.msgbox('NOT FOUND MESSAGES!')
        return
    while i < len(data):
        for v in data[i].values():
            value.append(str(v) + '  ')
        i = i + 1
    for i in range(len(value)):
        s += value[i]
        if i % 4 == 3:
            val_p.append(s)
            s = ''
    if len(a) == 1:
        return val_p
    tem = easygui.multchoicebox(msg=m, title=t,
                                choices=val_p)
    return tem      #返回要修改的原值


def tip_not_found_file():
    easygui.msgbox('NOT FOUND MESSAGES!', 'tip')

仅供学习交流!

三,一些废话

总共不到300行,python的确是一门简洁的语言,用c的话估计冲着五六百行就去了,python作为辅助语言不错,但不建议作为第一语言来使用。隐去了很多我们不需要考虑的内容。

主要参考资料:
1,《Python编程从入门到实践》,人民邮电出版社
2,python简单图形界面GUI入门——easygui
https://blog.csdn.net/mingqi1996/article/details/81272621

你可能感兴趣的:(经验分享,python)