python: tkinter graphical interface address book + txt text storage data

1 Experimental purpose and requirements

The purpose of the experiment: to design a practical small address book program

Experimental requirements: the last address book should be written into a file and saved

2 Experimental content

The content of this experiment is as follows:

Design a practical small address book program with add, query and delete functions. It consists of name, place of origin, phone number 1, phone number 2, and email address. The name can be coded by a mixture of characters and numbers. Phone numbers can consist of characters and numbers.

Requirement: the last address book is saved in the file to be written;

Realize the function:

(1) The system works in menu mode

(2) Information entry function

(3) Information browsing function

(4) Information query function

(5) Information modification function

(6) System exit function

3 main experimental steps

(1) Import the required libraries: tkinter.messagebox is used to display message boxes, json is used to process JSON data, os is used for file operations, and tkinter is used to create GUI interfaces.

(2) Create the main window: root = tkinter.Tk() Create a main window and set the title and size.

(3) Add scrollbar: Create a vertical scrollbar and associate it with the list box.

(4) Create an address book display area: use Frame to create a frame in the main window for displaying address book information, including contact name, mobile phone number, etc.

(5) Open the address book file: Open the file named "Address Book.txt" in the current directory, and create a new file if the file does not exist.

(6) Define the function showinfo(): used to display the contact information in the address book.

(7) Create buttons and input boxes: including add contacts, delete contacts, modify contacts, find contacts, and exit buttons, as well as an input box for entering the name of the contact.

(8) Binding button events: Bind the click events of adding contacts, deleting contacts, modifying contacts, finding contacts and exit buttons respectively, and the corresponding functions will be executed when the buttons are clicked.

(9) Run the main loop: Use "root.mainloop()" to run the event loop of the main window, so that the window can respond to user operations.

4 Experimental process

4.1 Import required modules

Import three modules: tkinter.messagebox, json and os.

import tkinter.messagebox

import json

import us

import tkinter

in:

The tkinter.messagebox module provides some functions for displaying message boxes in GUI programs;

The json module provides some functions for reading and writing JSON data;

The os module provides some functions for interacting with the operating system.

A module called tkinter is also imported here, which is a graphical user interface (GUI) toolkit built into Python and is often used when developing desktop applications.

4.2 Create the main window

Use tkinter.Tk() to create a main window named root, and set the title of the window to "Contacts" and the size of the window to 550x500.

root = tkinter.Tk()

root.title(' Contacts')

root.geometry("550x500")

This code is to use the tkinter module in Python to create a window named "root" (or call it the main window). in:

The tkinter.Tk() method creates a top-level window object and assigns it to the variable root. This window object will serve as the parent container for all other widgets.

The root.title() method sets the title of the main window as "Contacts".

The root.geometry() method is used to set the size of the main window to be 550 pixels wide and 500 pixels high. In Python, you can specify parameters such as the size and position of the window through strings. For example, the "550x500" string in this code means to set the window width to 550 pixels and height to 500 pixels.

4.3 Add scroll bar

Create a vertical scrollbar and place it on the right side of the main window.

scrollbar = tkinter.Scrollbar(root)

scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)

This code creates a scrollbar object called "scrollbar" in the root window (the main window) using the tkinter module. in:

The tkinter.Scrollbar() method creates a Scrollbar component object and assigns it to the variable scrollbar.

The scrollbar.pack() method is used to place the scrollbar widget on the right side of the main window and fill its Y axis.

The pack() method here is the simplest layout manager in tkinter. It is more commonly used in GUI development. It can make widgets adapt to size and arrange them together, but it can only achieve relatively simple layout requirements. If you need more flexible and advanced layout control, you can use other layout managers, such as grid() or place(), etc.

4.4 Create a contact list box

Create a frame Frame_info to hold the contact list box. Create a listbox listbox in the frame and bind the vertical scrollbar to the listbox.

Frame_info = tkinter.Frame(root, height=150, width=180)

Frame_info.place(x=40, y=80)

listbox = tkinter.Listbox(Frame_info, yscrollcommand=scrollbar.set, font=('宋体', 15))

listbox.grid(row=2, column=0, columnspan=5, sticky=tkinter.NSEW)

scrollbar.config(command=listbox.yview)

This code uses the tkinter module to create a frame object named "Frame_info" and a listbox object named "listbox" in the root window (main window), and places them in the specified position of the main window. in:

The tkinter.Frame() method creates a Frame component object and assigns it to the variable Frame_info. This component is typically used as a container for other widgets to better manage their layout.

The Frame_info.place() method is used to place the Frame_info component at the specified position of the main window (x=40, y=80).

The listbox = tkinter.Listbox(Frame_info,...) method creates a Listbox component object and assigns it to the variable listbox. This component is used to display a scrollable text list.

The setting parameters in the listbox.grid(...) method are used to set the display properties such as the offset and size of the listbox object in the Frame_info frame.

scrollbart.config(command=listbox.yview) is used to realize the associated scrollbar and the corresponding text list.

Here sticky=tkinter.NSEW means to enable the component to expand and fill the space in the frame, so as to adapt to the size and occupy the entire grid. If sticky is not specified, it will only occupy the minimum required space and cannot be expanded adaptively.

4.5 Open the address book file and display the contact information:

file = open(" Contacts.txt", mode='a', encoding='utf-8')

file.close()

This attempts to open the file named "Contacts.txt" in append mode, creating an empty file if it does not exist. Then close the file immediately.

def showinfo():

    listbox.delete(0, tkinter.END)

    file = open(" Contacts.txt", mode='r', encoding='utf-8')

    if len(file.read()) != 0:

        file.seek(0, 0)

        file_data = file.read()

        split_info = file_data.split('\n')

        split_info.remove(split_info[len(split_info) - 1])

        name_li = []

        all_info_li = []

        for i in split_info:

            dict_info = json.loads(i.replace("\'", '\"'))

            all_info_li.append(dict_info)

            listbox.insert(tkinter.END, dict_info[' name'] + ' ' + dict_info['mobile number 1'] + ' ' + dict_info['mobile number 2'] + ' ' +

                           dict_info[' email'] + ' ' + dict_info['address'])

file.close()

A showinfo() function is defined to display contact information. The function first clears the content of the listbox listbox, then opens the address book file and reads the information in it. By parsing the JSON string, add the information of each contact to the all_info_li list, and insert the name and other information into the list box after splicing. Finally close the file. in:

The listbox.delete(0, tkinter.END) method is used to clear all the data in the previous listbox.

file = open("Address Book.txt", mode='r', encoding='utf-8') opens the file named "Address Book.txt", and assigns the file object to the variable file. mode='r' means to open the file in read-only mode, and encoding='utf-8' specifies the encoding format of the file.

len(file.read()) != 0 is used to determine whether the current file is empty. If it is not empty, it means that there is address book information that needs to be displayed.

file.seek(0, 0) means to move the file pointer to the beginning of the file.

file_data = file.read() reads the entire file into a string variable file_data.

split_info = file_data.split('\n') uses the split() method to split the file content into substrings according to newline characters, and returns a list split_info.

split_info.remove(split_info[len(split_info) - 1]) removes the last empty string element of the list split_info.

In the for loop, each substring i in the list split_info is traversed one by one. First use the json.loads() method to parse the JSON format data in the string, and then add it to the list all_info_li for saving. Next, insert the analyzed address book data information into the listbox according to the specified format.

Finally, remember to close the file to prevent file handle resource leaks.

4.6 Add contact function

def add_def():

    add_info = {' Name': '', 'Mobile Number 1': '', 'Mobile Number 2': '', 'Email': '', 'Address': ''}

    add_info['姓名'] = name_input.get()

    if add_info[' name'] == '':

        tkinter.messagebox.showinfo(' Prompt', 'Please enter your name!')

        return

    add_info[' mobile number 1'] = pho_input.get()

    add_info[' mobile number 2'] = pho_input2.get()

    add_info[' email'] = email_input.get()

    add_info['地址'] = address_input.get()

    with open(" Contacts.txt", 'a+', encoding='utf-8') as file:

        file.write(str(add_info) + '\n')

    showinfo()

    name_input.delete(0, tkinter.END)

    pho_input.delete(0, tkinter.END)

    pho_input2.delete(0, tkinter.END)

    email_input.delete(0, tkinter.END)

address_input.delete(0, tkinter.END)

An add_def() function is defined for adding contacts. The function first creates an empty contact information dictionary add_info, then obtains the contact's name, mobile phone number, email address and address from the input box, and fills them into the dictionary. Next, write the contact information into the address book file in string form. Finally, call the showinfo() function to refresh the content of the list box and clear the content in the input box. in:

add_info = {'Name': '', 'Mobile Number 1': '', 'Mobile Number 2': '', 'Email': '', 'Address': ''} Create an empty dictionary add_info.

add_info['name'] = name_input.get() Get the value in the name input box from the graphical interface, and save it to the "name" field of the dictionary add_info.

if add_info['name'] == '': used to determine whether the name is empty. If it is empty, a prompt box will pop up and the function will end.

add_info['phone number 1'] = pho_input.get() Obtain the value in the phone number 1 input box from the graphical interface, and save it to the "phone number 1" field of the dictionary add_info.

add_info['phone number 2'] = pho_input2.get() Obtain the value in the phone number 2 input box from the graphical interface, and save it to the "phone number 2" field of the dictionary add_info.

add_info['email'] = email_input.get() Gets the value in the email input box from the graphical interface, and saves it in the "email" field of the dictionary add_info.

add_info['address'] = address_input.get() Gets the value in the address input box from the graphical interface, and saves it into the "address" field of the dictionary add_info.

with open("Address Book.txt", 'a+', encoding='utf-8') as file: Open the file named "Address Book.txt", and assign the file object to the variable file. mode='a+' indicates that the file is opened in append mode, and the encoding format of the specified file is utf-8.

file.write(str(add_info) + '\n') writes the dictionary add_info to the file as a string and adds a newline at the end.

showinfo() calls the "showinfo()" function to refresh the data display part of the address book.

Finally, clear the data in each input box and continue to wait for user input.

4.7 Delete contact function

def del_def():

    selected_item = listbox.curselection()

    if not selected_item:

        tkinter.messagebox.showinfo(' Prompt', 'Please select the contact to delete!')

        return

    else:

        file = open(" Contacts.txt", mode='r', encoding='utf-8')

        read_data = file.readlines()

        file.close()

        selected_index = selected_item[0]

        del read_data[selected_index]

        file = open(" Contacts.txt", mode='w', encoding='utf-8')

        file.writelines(read_data)

        file.close()

        showinfo()

A del_def() function is defined to delete the selected contact. First check whether the contact is selected, if not selected, a prompt box will pop up. If there are selected contacts, opens the address book file and reads its contents line by line. After finding the index for the selected contact, delete the corresponding line and rewrite the remaining content to the file. Finally, call the showinfo() function to refresh the contents of the list box. in:

selected_item = listbox.curselection() Obtain the contact selected by the user in the graphical interface through the "curselection()" method, and save it to the variable selected_item.

if not selected_item: Determine whether the user has selected the contact to be deleted. If there is no selection, a prompt box will pop up and the function will end.

file = open("Address Book.txt", mode='r', encoding='utf-8') opens the file named "Address Book.txt", and assigns the file object to the variable file. mode='r' indicates that the file is opened in read-only mode, and the encoding format of the specified file is utf-8. Note that you need to confirm that the file has been created before doing this.

read_data = file.readlines() reads all the lines in the file and saves them into the list read_data.

file.close() closes the file.

selected_index = selected_item[0] Get the index value of the contact selected by the user and save it to the variable selected_index.

del read_data[selected_index] Deletes the data of the contact selected by the user from the list read_data.

file = open("Contacts.txt", mode='w', encoding='utf-8') re-open the file in writing mode, and assign the file object to the variable file. mode='w' means to open the file in overwrite mode, and the encoding format of the specified file is utf-8.

file.writelines(read_data) rewrites all the processed data to the file.

file.close() closes the file.

showinfo() calls the "showinfo()" function to refresh the data display part of the address book.

4.8 Modify contact function

def update_def():

    selected_item = listbox.curselection()

    if not selected_item:

        tkinter.messagebox.showinfo(' Prompt', 'Please select the contact to modify!')

        return

    else:

        file = open(" Contacts.txt", mode='r', encoding='utf-8')

        read_data = file.readlines()

        file.close()

        selected_index = selected_item[0]

        selected_info = json.loads(read_data[selected_index].replace("\'", '\"'))

        name_input.insert(0, selected_info['姓名'])

        pho_input.insert(0, selected_info[' mobile number 1'])

        pho_input2.insert(0, selected_info[' mobile number 2'])

        email_input.insert(0, selected_info[' email'])

        address_input.insert(0, selected_info['地址'])

        del read_data[selected_index]

        file = open(" Contacts.txt", mode='w', encoding='utf-8')

        file.writelines(read_data)

        file.close()

        showinfo()

An update_def() function is defined for modifying the selected contact. First check whether the contact is selected, if not selected, a prompt box will pop up. If there are selected contacts, opens the address book file and reads its contents line by line. After finding the index of the selected contact, parse its information into a dictionary and fill the corresponding value into the corresponding input box. Then delete the selected contact information and rewrite the remaining content to the file. Finally, call the showinfo() function to refresh the contents of the list box.

This code defines a function named "update_def()", which implements the function of modifying the address book information. in:

selected_item = listbox.curselection() Obtain the contact selected by the user in the graphical interface through the "curselection()" method, and save it to the variable selected_item.

if not selected_item: Determine whether the user has selected the contact to be modified. If there is no selection, a prompt box will pop up and the function will end.

file = open("Address Book.txt", mode='r', encoding='utf-8') opens the file named "Address Book.txt", and assigns the file object to the variable file. mode='r' indicates that the file is opened in read-only mode, and the encoding format of the specified file is utf-8. Note that you need to confirm that the file has been created before doing this.

read_data = file.readlines() reads all the lines in the file and saves them into the list read_data.

file.close() closes the file.

selected_index = selected_item[0] Get the index value of the contact selected by the user and save it to the variable selected_index.

selected_info= json.loads(read_data[selected_index].replace("\'", '\"')) Get the contact information selected by the user from read_data and convert it into dictionary format data (because single quotes are used, need to be replaced with double quotes first).

name_input.insert(0, selected_info['name']) Display the name information of the selected contact in the corresponding text box.

pho_input.insert(0, selected_info['phone number 1']) displays the phone number 1 information of the selected contact in the corresponding text box.

pho_input2.insert(0, selected_info['phone number 2']) displays the phone number 2 information of the selected contact in the corresponding text box.

email_input.insert(0, selected_info['email']) will display the email information of the selected contact in the corresponding text box.

address_input.insert(0, selected_info['address']) Display the address information of the selected contact in the corresponding text box.

del read_data[selected_index] Deletes the data of the contact selected by the user from the list read_data.

file = open("Contacts.txt", mode='w', encoding='utf-8') re-open the file in writing mode, and assign the file object to the variable file. mode='w' means to open the file in overwrite mode, and the encoding format of the specified file is utf-8.

file.writelines(read_data) rewrites all the processed data to the file.

file.close() closes the file.

showinfo() calls the "showinfo()" function to refresh the data display part of the address book.

4.9 Create each component

name_label = tkinter.Label(root, text=' name:', font=('Arial', 15))

name_label.place(x=40, y=280)

name_input = tkinter.Entry(root, font=('宋体', 15))

name_input.place(x=90, y=280)

pho_label = tkinter.Label(root, text=' Mobile phone number 1:', font=('宋体', 15))

pho_label.place(x=10, y=330)

pho_input = tkinter.Entry(root, font=('宋体', 15))

pho_input.place(x=90, y=330)

pho_label2 = tkinter.Label(root, text=' Mobile phone number 2:', font=('宋体', 15))

pho_label2.place(x=10, y=380)

pho_input2 = tkinter.Entry(root, font=(' Arial', 15))

pho_input2.place(x=90, y=380)

email_label = tkinter.Label(root, text=' Email:', font=('Arial', 15))

email_label.place(x=40, y=430)

email_input = tkinter.Entry(root, font=(' Arial', 15))

email_input.place(x=90, y=430)

address_label = tkinter.Label(root, text=' Address:', font=('Arial', 15))

address_label.place(x=40, y=480)

address_input = tkinter.Entry(root, font=('宋体', 15))

address_input.place(x=90, y=480)

add_button = tkinter.Button(root, text=' Add', font=('Arial', 15), command=add_def)

add_button.place(x=420, y=280)

del_button = tkinter.Button(root, text=' Delete', font=('Arial', 15), command=del_def)

del_button.place(x=420, y=330)

update_button = tkinter.Button(root, text=' modify', font=('宋体', 15), command=update_def)

update_button.place(x=420, y=380)

quit_button = tkinter.Button(root, text=' quit', font=('宋体', 15), command=root.quit)

quit_button.place(x=420, y=430)

Create various GUI components such as labels, input boxes and buttons, and use the place() method to place them in the specified position of the main window. in:

Label creates a text label for displaying text content.

Entry Creates a text box for entering and displaying text content.

Button Creates a button that triggers the corresponding action.

The place(x, y) method is used to set the position coordinates of the component on the interface.

Specific location:

name_label creates a text label named "name" and places it at the coordinates of position (40, 280).

name_input creates a textbox for entering a name and places it at the coordinates of position (90, 280).

pho_label creates a text label called "Phone Number 1" and places it at the coordinates of location (10, 330).

pho_input creates a textbox for entering a mobile phone number and places it at the coordinates of position (90, 330).

pho_label2 creates a text label called "Phone Number 2" and places it at the coordinates of location (10, 380).

pho_input2 creates another textbox for entering a mobile number and places it at the coordinates of position (90, 380).

email_label creates a text label called "email" and places it at the coordinates of position (40, 430).

email_input creates a textbox for entering email and places it at the coordinates of position (90, 430).

address_label creates a text label called "address" and places it at the coordinates of location (40, 480).

address_input creates a textbox for entering an address and places it at the coordinates of location (90, 480).

Next are four buttons:

add_button creates a button called "Add" and places it at the coordinates of position (420, 280). The button triggers the add_def() function to realize the function of adding contact information.

del_button creates a button called "Delete" and places it at the coordinates of position (420, 330). The button triggers the del_def() function to realize the function of deleting contact information.

update_button creates a button called "Update" and places it at the coordinates of position (420, 380). The button triggers the update_def() function to realize the function of modifying the contact information.

quit_button creates a button called "Add" and places it at the coordinates of position (420, 430). This button implements the exit function.

4.10 Display Contact Information

showinfo()

Call the showinfo() function to display the existing contact information during initialization.

4.11 Running the main loop

root.mainloop()

The main loop of the GUI application is started by calling the mainloop() method, waiting for user interaction events to occur.

The above is the detailed implementation process of the code. A simple address book application is implemented by creating GUI windows, reading files, adding, deleting and modifying contacts. Users can input contact information on the interface, and then add, delete, modify and query contacts through button operations.

【Complete code】

import tkinter.messagebox
import json
import os
import tkinter

root = tkinter.Tk()
root.title('通讯录')
root.geometry("550x500")

# 添加滚动条
scrollbar = tkinter.Scrollbar(root)
scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y)

Frame_info = tkinter.Frame(root, height=150, width=180)
Frame_info.place(x=40, y=80)#滚动框位置

# 绑定滚动条和列表
listbox = tkinter.Listbox(Frame_info, yscrollcommand=scrollbar.set, font=('宋体', 15))
listbox.grid(row=2, column=0, columnspan=5, sticky=tkinter.NSEW)

# 设置滚动条和列表的关系
scrollbar.config(command=listbox.yview)
#

#标题属性的另一个设置方法
# name_label = tkinter.Label(Frame_info, text="名字", font=('宋体', 15))
# name_label.grid(row=1, column=0)
# phone_label = tkinter.Label(Frame_info, text="手机号1", font=('宋体', 15))
# phone_label.grid(row=1, column=1)
# phone_label = tkinter.Label(Frame_info, text="手机号2", font=('宋体', 15))
# phone_label.grid(row=1, column=2)
# mail_label = tkinter.Label(Frame_info, text="邮箱", font=('宋体', 15))
# mail_label.grid(row=1, column=3)
# address_label = tkinter.Label(Frame_info, text="地址", font=('宋体', 15))
# address_label.grid(row=1, column=4)


file = open("通讯录.txt", mode='a', encoding='utf-8')
file.close()

def showinfo():
    # 清空列表
    listbox.delete(0, tkinter.END)

    file = open("通讯录.txt", mode='r', encoding='utf-8')
    if len(file.read()) != 0:
        file.seek(0, 0)
        file_data = file.read()
        split_info = file_data.split('\n')
        split_info.remove(split_info[len(split_info) - 1])
        name_li = []  # 用于存储联系人姓名的列表
        all_info_li = []  # 用于存储所有信息的列表
        for i in split_info:
            dict_info = json.loads(i.replace("\'", '\"'))
            all_info_li.append(dict_info)
            # 添加到列表中
            listbox.insert(tkinter.END, dict_info['姓名'] + ' ' + dict_info['手机号1'] + ' ' + dict_info['手机号2'] + ' ' +
                           dict_info['邮箱'] + ' ' + dict_info['地址'])
            row_count = 0
            column_count = 0

        # for i in all_info_li:
        #     # row_count += 1
        #     column_count += 1

            # for title, info_value in person_info.items():
            #     tktest = tkinter.Label(Frame_info, text=info_value, font=('宋体', 15, 'bold'))
            #     tktest.grid(row=row_count, column=column_count)
            #     column_count += 1
            # row_count += 1
            tktest = tkinter.Label(Frame_info, text=" " *42, font=('宋体', 15, 'bold'))#设置滚动框显示的宽度
            tktest.grid(row=row_count, column=column_count)


showinfo()

# 添加
def add_def(event):
    def add_man(event):
        name = name_new.get()
        phone1 = phone_new1.get()
        phone2 = phone_new2.get()
        mail = mail_new.get()
        address = adr_new.get()
        if name == "" or phone1 == " " or phone2 == " " or mail == " " or address == " ":
            tkinter.messagebox.showerror('错误', '所填信息都不能为空')
        else:
            card_dict = {"姓名": name, "手机号1": phone1, "手机号2": phone2,
                         "邮箱": mail, "地址": address}
            f = open("通讯录.txt", mode='a+', encoding='utf-8')
            f.write(str(card_dict) + '\n')
            f.close()
            tkinter.messagebox.showinfo('消息提示框', f'添加“{name}“为联系人成功!')
            showinfo()
            window_add.destroy()



    # 弹出框
    window_add = tkinter.Toplevel(root)
    window_add.geometry('300x250')
    # 姓名
    name_new = tkinter.StringVar()
    tkinter.Label(window_add, text='新联系人姓      名:').place(x=10, y=10)
    tkinter.Entry(window_add, textvariable=name_new).place(x=130, y=10)
    # 手机号1
    phone_new1 = tkinter.StringVar()
    tkinter.Label(window_add, text='新联系人手机号1:').place(x=10, y=50)
    tkinter.Entry(window_add, textvariable=phone_new1).place(x=130, y=50)
    # 手机号2
    phone_new2 = tkinter.StringVar()
    tkinter.Label(window_add, text='新联系人手机号2:').place(x=10, y=90)
    tkinter.Entry(window_add, textvariable=phone_new2).place(x=130, y=90)
    # 邮箱
    mail_new = tkinter.StringVar()
    tkinter.Label(window_add, text='新联系人邮      箱:').place(x=10, y=130)
    tkinter.Entry(window_add, textvariable=mail_new).place(x=130, y=130)
    # 地址
    adr_new = tkinter.StringVar()
    tkinter.Label(window_add, text='新联系人地      址:').place(x=10, y=170)
    tkinter.Entry(window_add, textvariable=adr_new).place(x=130, y=170)
    # 确认
    confirm_button = tkinter.Button(window_add, text='确认添加', font=('宋体', 15))
    confirm_button.bind("<Button-1>", add_man)
    confirm_button.place(x=100, y=200)

# 删除
def del_def(event):
    name = man_name.get()
    file = open("通讯录.txt", mode='r+', encoding='utf-8')
    if len(file.read()) != 0:
        file.seek(0, 0)
        file_data = file.read()
        split_info = file_data.split('\n')
        split_info.remove(split_info[len(split_info) - 1])
        name_li = []
        all_info_li = []
        for i in split_info:
            dict_info = json.loads(i.replace("\'", '\"'))
            all_info_li.append(dict_info)
            name_li.append(dict_info['姓名'])
        if name in name_li:
            通讯录_copy = open('通讯录_copy.txt', mode='w+', encoding="utf-8")
            for person_info in all_info_li:
                if name not in str(person_info):
                    通讯录_copy.write(str(person_info) + '\n')
            通讯录_copy.close()
            file.close()
            os.rename('通讯录.txt', '通讯录_del.txt')
            os.rename('通讯录_copy.txt', '通讯录.txt')
            os.remove('通讯录_del.txt')
            tkinter.messagebox.showinfo('消息提示', f'删除“{name}“成功!')
            showinfo()
        else:
            tkinter.messagebox.showinfo('消息提示', '查无此人!')


# 修改
def update_def(event):
    def update_man(event):
        name = name_new.get()
        phone1 = phone_new1.get()
        phone2 = phone_new2.get()
        mail = mail_new.get()
        address = address_new.get()
        if name != "" and phone1 != "" and phone2 != "" and mail != "" and address != "":
            通讯录_copy = open('通讯录_copy.txt', mode='w', encoding="utf-8")
            # 将数据封装到字典中
            card_dict = {"姓名": name, "手机号1": phone1, "手机号2": phone2,
                         "邮箱": mail, "地址": address}
            for person_info in all_info_li:
                if name_old in str(person_info):
                    person_info = str(card_dict)
                通讯录_copy.write(str(person_info) + '\n')
            通讯录_copy.close()
            file.close()
            os.rename('通讯录.txt', '通讯录_del.txt')
            os.rename('通讯录_copy.txt', '通讯录.txt')
            os.remove('通讯录_del.txt')
            tkinter.messagebox.showinfo('消息提示框', '更新成功!')
            showinfo()
        else:
            tkinter.messagebox.showinfo('消息提示框', '请输入正确信息,或输入完整信息')
    name_old = man_name.get()
    file = open("通讯录.txt", mode='r+', encoding='utf-8')
    if len(file.read()) != 0:
        file.seek(0, 0)
        file_data = file.read()
        split_info = file_data.split('\n')
        split_info.remove(split_info[len(split_info) - 1])
        name_li = []
        all_info_li = []
        for i in split_info:
            dict_info = json.loads(i.replace("\'", '\"'))
            all_info_li.append(dict_info)
            name_li.append(dict_info['姓名'])
        if name_old in name_li:
            window_update = tkinter.Toplevel(root)
            window_update.geometry('280x200')
            # 输入更新的信息
            name_new = tkinter.StringVar()
            phone_new1 = tkinter.StringVar()
            phone_new2 = tkinter.StringVar()
            mail_new = tkinter.StringVar()
            address_new = tkinter.StringVar()
            # 输入更改后的信息
            tkinter.Label(window_update, text='姓      名:').place(x=20, y=0)
            tkinter.Entry(window_update, textvariable=name_new).place(x=90, y=0)
            tkinter.Label(window_update, text='手机号1:').place(x=20, y=30)
            tkinter.Entry(window_update, textvariable=phone_new1).place(x=90, y=30)
            tkinter.Label(window_update, text='手机号2:').place(x=20, y=60)
            tkinter.Entry(window_update, textvariable=phone_new2).place(x=90, y=60)
            tkinter.Label(window_update, text='邮      箱:').place(x=20, y=90)
            tkinter.Entry(window_update, textvariable=mail_new).place(x=90, y=90)
            tkinter.Label(window_update, text='地      址:').place(x=20, y=120)
            tkinter.Entry(window_update, textvariable=address_new).place(x=90, y=120)
            # 确认
            confirm_button = tkinter.Button(window_update, text='确认修改', font=('宋体', 15))
            confirm_button.bind("<Button-1>", update_man)
            confirm_button.place(x=100, y=150)
        else:
            tkinter.messagebox.showinfo('消息提示', '通讯录中查无此人')

# 查找
def find_def(event):
    name = man_name.get()
    file = open("通讯录.txt", mode='r+', encoding='utf-8')
    if len(file.read()) != 0:
        file.seek(0, 0)
        file_data = file.read()
        split_info = file_data.split('\n')
        split_info.remove(split_info[len(split_info) - 1])
        name_li = []
        all_info_li = []
        for i in split_info:
            dict_info = json.loads(i.replace("\'", '\"'))
            all_info_li.append(dict_info)
            name_li.append(dict_info['姓名'])
        if name in name_li:
            man_find = tkinter.Toplevel(root)
            man_find.geometry('400x140')
            for person_info in all_info_li:
                if name in str(person_info):
                    for title, info_value in person_info.items():
                        tem_text = title + ":" + info_value + " " *10
                        tktest = tkinter.Label(man_find, text=tem_text, font=('宋体', 15))
                        tktest.pack(side="top", anchor='w')
        else:
            tkinter.messagebox.showinfo('消息提示', '通讯录中查无此人')

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

# 输入框
man_nametitle = tkinter.Label(root,text="请输入联系人姓名:", font=('宋体', 10)).place(x=40,y=358)#x为距离左侧距离
man_name = tkinter.StringVar()
tkinter.Entry(root, textvariable=man_name, width=28).place(x=160, y=355)#输入框位置

# 联系人名单标题
man_nametitle = tkinter.Label(root,text="联系人名单列表", font=('宋体', 20, 'bold')).place(x=180,y=35)
man_nametitle = tkinter.Label(root,text="-"*150,).place(x=0,y=10)

#属性标题
man_nametitle = tkinter.Label(root,text="姓名    手机号1    手机号2      邮箱   地址", font=('宋体', 15, 'bold')).place(x=44,y=75)
man_nametitle = tkinter.Label(root,text="-"*150,).place(x=0,y=10)
# 添加
button1 = tkinter.Button(root, text="添加联系人", width=10, height=2,font=('宋体', 15))
button1.place(x=40, y=400)
button1.bind('<Button-1>', add_def)

# 删除
button3 = tkinter.Button(root, text="删除联系人", width=10,height=2, font=('宋体', 15))
button3.place(x=280, y=400)
button3.bind('<Button-1>', del_def)

# 修改
button4 = tkinter.Button(root, text="修改联系人", width=10,height=2, font=('宋体', 15))
button4.place(x=160, y=400)
button4.bind('<Button-1>', update_def)

# 查找
button5 = tkinter.Button(root, text="查找联系人", width=10, font=('宋体', 15))
button5.place(x=398, y=350)
button5.bind('<Button-1>', find_def)

# 退出
button6 = tkinter.Button(root, text="退出", width=10, height=2, font=('宋体', 15))
button6.place(x=398, y=400)
button6.bind('<Button-1>', over_def)

root.mainloop()  # 显示主窗体

5 Experimental results

6 Experiment summary

The design process of this experiment can be said to have gone through various ups and downs, and the amount of code is quite a lot, with a total of 293 lines (including comments).

Among them, the file storage and reading operation design part, because I use the dictionary operation, it needs special conversion for storage and reading, and the algorithm involved is finally successfully passed after continuous debugging.

In the process of visual design, many factors are considered, including the layout of buttons and text boxes, the internal transfer parameters of functions, the program processing of special cases, the design of menus and so on. In the process of menu design, by searching a large number of blogs and reading other people's codes, I learned the design method of passing position parameters, and it was applied and reflected in this design experiment. In the interface design process, since there are only three functions (pack(), grid(), place()) that can adjust the layout in python, and the use of the function requires input of different parameters to control its display position, so in the process In order to make the interface as beautiful as possible, I went through a long layout process. However, there are still some deficiencies that cannot be debugged, such as modifying the layout of each button and text box in the pop-up window, there are still some blank parts that cannot be filled.

Although the overall process has some ups and downs, fortunately, we have tried our best to solve the known problems. This design experiment has fully exercised my ability to call the tkinter module to design the layout, which has a significant improvement. At the same time, I also found that it is indeed a little difficult to use the python environment to do visual design. Some internal module functions need to be continuously updated. Design The layout function is not user-friendly and convenient enough. However, in order to fully exercise my python programming ability, I overcame obstacles, which can be regarded as a victory.

Guess you like

Origin blog.csdn.net/weixin_55988897/article/details/131161712