请用python编写一个图形用户界面程序,设计一个通讯录界面,包含增删改查功能
时间: 2024-12-18 17:20:06 浏览: 19
为了创建一个简单的图形用户界面 (GUI) 程序,我们可以使用 Python 的 Tkinter 库,这是一个内置库,非常适合初学者入门。我们将设计一个基本的通讯录应用,包括添加、删除、修改和查询联系人。以下是代码示例:
```python
import tkinter as tk
from tkinter import messagebox
class ContactBookApp(tk.Tk):
def __init__(self):
super().__init__()
self.contacts = []
# 设计主窗口
self.title("通讯录")
self.geometry("400x500")
# 创建标签和输入框
self.name_label = tk.Label(text="姓名:")
self.name_entry = tk.Entry()
self.phone_label = tk.Label(text="电话:")
self.phone_entry = tk.Entry()
# 添加按钮
self.add_button = tk.Button(text="添加", command=self.add_contact)
self.delete_button = tk.Button(text="删除", command=self.delete_contact)
self.update_button = tk.Button(text="更新", command=self.update_contact)
self.search_button = tk.Button(text="搜索", command=self.search_contact)
# 将控件布局到窗口上
self.name_label.pack()
self.name_entry.pack()
self.phone_label.pack()
self.phone_entry.pack()
self.add_button.pack()
self.delete_button.pack()
self.update_button.pack()
self.search_button.pack()
def add_contact(self):
name = self.name_entry.get()
phone = self.phone_entry.get()
if not name or not phone:
messagebox.showerror("错误", "请输入完整的联系信息")
else:
self.contacts.append({"name": name, "phone": phone})
self.name_entry.delete(0, tk.END)
self.phone_entry.delete(0, tk.END)
def delete_contact(self):
name = self.name_entry.get()
if not name:
messagebox.showerror("错误", "请选择要删除的联系人")
else:
for contact in self.contacts:
if contact["name"] == name:
self.contacts.remove(contact)
break
self.name_entry.delete(0, tk.END)
self.phone_entry.delete(0, tk.END)
def update_contact(self):
name = self.name_entry.get()
new_phone = self.phone_entry.get()
if not name or not new_phone:
messagebox.showerror("错误", "请输入新的联系信息")
else:
for idx, contact in enumerate(self.contacts):
if contact["name"] == name:
self.contacts[idx]["phone"] = new_phone
break
self.name_entry.delete(0, tk.END)
self.phone_entry.delete(0, tk.END)
def search_contact(self):
keyword = self.name_entry.get()
if keyword:
results = [contact for contact in self.contacts if keyword in contact["name"]]
print(f"搜索结果:{results}")
else:
messagebox.showinfo("提示", "请输入关键词进行搜索")
# 运行主程序
app = ContactBookApp()
app.mainloop()
```
阅读全文