import tkinter as tk
import pickle

# Function to save contacts to a file
def save_contacts(contacts):
    with open("contacts.pkl", "wb") as file:
        pickle.dump(contacts, file)

# Function to add a new contact
def add_contact():
    name = name_entry.get()
    phone = phone_entry.get()
    contacts.append({"name": name, "phone": phone})
    contact_listbox.insert(tk.END, f"{name} - {phone}")
    save_contacts(contacts)

# Initialize Tkinter
root = tk.Tk()
root.title("Contact Manager")

# Create GUI elements
name_label = tk.Label(root, text="Name:")
name_label.pack()
name_entry = tk.Entry(root)
name_entry.pack()

phone_label = tk.Label(root, text="Phone:")
phone_label.pack()
phone_entry = tk.Entry(root)
phone_entry.pack()

add_button = tk.Button(root, text="Add Contact", command=add_contact)
add_button.pack()

contact_listbox = tk.Listbox(root)
contact_listbox.pack()

# Load existing contacts or create an empty list
try:
    with open("contacts.pkl", "rb") as file:
        contacts = pickle.load(file)
        for contact in contacts:
            contact_listbox.insert(tk.END, f"{contact['name']} - {contact['phone']}")
except FileNotFoundError:
    contacts = []

root.mainloop()