使用tkinter实现简单的通讯录功能
时间: 2023-12-14 10:04:53 浏览: 124
以下是使用tkinter实现简单通讯录功能的示例代码:
```python
import tkinter as tk
class Contact:
def __init__(self, name, phone, email):
self.name = name
self.phone = phone
self.email = email
class App:
def __init__(self, master):
self.master = master
self.master.title("通讯录")
self.master.geometry("400x300")
# 创建控件
self.name_label = tk.Label(self.master, text="姓名:")
self.name_entry = tk.Entry(self.master)
self.phone_label = tk.Label(self.master, text="电话:")
self.phone_entry = tk.Entry(self.master)
self.email_label = tk.Label(self.master, text="邮箱:")
self.email_entry = tk.Entry(self.master)
self.add_button = tk.Button(self.master, text="添加", command=self.add_contact)
self.show_button = tk.Button(self.master, text="显示", command=self.show_contacts)
self.clear_button = tk.Button(self.master, text="清空", command=self.clear_entries)
self.listbox = tk.Listbox(self.master, width=50)
# 布局控件
self.name_label.grid(row=0, column=0, padx=5, pady=5, sticky="w")
self.name_entry.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
self.phone_label.grid(row=1, column=0, padx=5, pady=5, sticky="w")
self.phone_entry.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
self.email_label.grid(row=2, column=0, padx=5, pady=5, sticky="w")
self.email_entry.grid(row=2, column=1, padx=5, pady=5, sticky="ew")
self.add_button.grid(row=3, column=0, padx=5, pady=5, sticky="ew")
self.show_button.grid(row=3, column=1, padx=5, pady=5, sticky="ew")
self.clear_button.grid(row=3, column=2, padx=5, pady=5, sticky="ew")
self.listbox.grid(row=4, column=0, columnspan=3, padx=5, pady=5, sticky="ew")
# 初始化通讯录列表
self.contacts = []
def add_contact(self):
name = self.name_entry.get()
phone = self.phone_entry.get()
email = self.email_entry.get()
contact = Contact(name, phone, email)
self.contacts.append(contact)
self.clear_entries()
def show_contacts(self):
self.listbox.delete(0, tk.END)
for contact in self.contacts:
self.listbox.insert(tk.END, f"{contact.name} {contact.phone} {contact.email}")
def clear_entries(self):
self.name_entry.delete(0, tk.END)
self.phone_entry.delete(0, tk.END)
self.email_entry.delete(0, tk.END)
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
root.mainloop()
```
运行代码后,将会弹出一个窗口,包含姓名、电话、邮箱的输入框,以及添加、显示、清空按钮和通讯录列表框。用户可以输入联系人的信息,然后点击添加按钮将联系人添加到通讯录列表中。点击显示按钮将会显示通讯录中所有联系人的信息。点击清空按钮将会清空输入框中的内容。
阅读全文