使用 Python + Tkinter + SQLite 製作的「簡易通訊錄」桌面應用程式
這個版本不需要額外安裝任何第三方套件(皆為 Python 內建標準函式庫),資料會自動儲存在本地的 contacts.db 資料庫中,並支援新增、修改、刪除、關鍵字搜尋以及匯出 CSV 功能。
完整程式碼 (address_book.py)
Python
import csv
import sqlite3
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
class AddressBookApp:
def __init__(self, root):
self.root = root
self.root.title("簡易通訊錄管理系統")
self.root.geometry("780x520")
self.root.resizable(True, True)
# 初始化資料庫
self.db_name = "contacts.db"
self.init_db()
# 當前選取的資料 ID
self.selected_id = None
# 建立介面
self.setup_ui()
self.load_data()
def init_db(self):
"""建立 SQLite 資料表"""
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
phone TEXT NOT NULL,
email TEXT,
group_name TEXT,
note TEXT
)
""")
conn.commit()
def setup_ui(self):
"""建立畫面元件"""
# --- 上方:輸入表單區 ---
form_frame = ttk.LabelFrame(
self.root, text="聯絡人資料", padding=(10, 10)
)
form_frame.pack(fill="x", padx=10, pady=5)
# 第一列:姓名、電話、群組
ttk.Label(form_frame, text="姓名 *:").grid(
row=0, column=0, sticky="e", pady=5
)
self.name_var = tk.StringVar()
ttk.Entry(form_frame, textvariable=self.name_var, width=18).grid(
row=0, column=1, padx=5, pady=5
)
ttk.Label(form_frame, text="電話 *:").grid(
row=0, column=2, sticky="e", pady=5
)
self.phone_var = tk.StringVar()
ttk.Entry(form_frame, textvariable=self.phone_var, width=18).grid(
row=0, column=3, padx=5, pady=5
)
ttk.Label(form_frame, text="群組:").grid(
row=0, column=4, sticky="e", pady=5
)
self.group_var = tk.StringVar(value="一般")
group_combo = ttk.Combobox(
form_frame,
textvariable=self.group_var,
values=["一般", "家人", "朋友", "同事", "廠商", "山友"],
width=15,
)
group_combo.grid(row=0, column=5, padx=5, pady=5)
# 第二列:Email、備註
ttk.Label(form_frame, text="Email:").grid(
row=1, column=0, sticky="e", pady=5
)
self.email_var = tk.StringVar()
ttk.Entry(form_frame, textvariable=self.email_var, width=18).grid(
row=1, column=1, padx=5, pady=5
)
ttk.Label(form_frame, text="備註:").grid(
row=1, column=2, sticky="e", pady=5
)
self.note_var = tk.StringVar()
ttk.Entry(form_frame, textvariable=self.note_var, width=44).grid(
row=1, column=3, columnspan=3, sticky="w", padx=5, pady=5
)
# --- 中間:操作按鈕與搜尋區 ---
btn_frame = ttk.Frame(self.root, padding=(10, 5))
btn_frame.pack(fill="x")
ttk.Button(btn_frame, text="新增", command=self.add_contact, width=8).pack(
side="left", padx=3
)
ttk.Button(
btn_frame, text="修改", command=self.update_contact, width=8
).pack(side="left", padx=3)
ttk.Button(
btn_frame, text="刪除", command=self.delete_contact, width=8
).pack(side="left", padx=3)
ttk.Button(
btn_frame, text="清空欄位", command=self.clear_fields, width=10
).pack(side="left", padx=3)
ttk.Button(
btn_frame, text="匯出 CSV", command=self.export_csv, width=10
).pack(side="left", padx=3)
# 搜尋框(靠右對齊)
ttk.Button(btn_frame, text="顯示全部", command=self.load_data).pack(
side="right", padx=3
)
ttk.Button(btn_frame, text="搜尋", command=self.search_contact).pack(
side="right", padx=3
)
self.search_var = tk.StringVar()
search_entry = ttk.Entry(
btn_frame, textvariable=self.search_var, width=18
)
search_entry.pack(side="right", padx=3)
search_entry.bind("<Return>", lambda event: self.search_contact())
ttk.Label(btn_frame, text="關鍵字:").pack(side="right")
# --- 下方:資料列表區 (Treeview) ---
table_frame = ttk.Frame(self.root, padding=(10, 5))
table_frame.pack(fill="both", expand=True)
columns = ("id", "name", "phone", "group", "email", "note")
self.tree = ttk.Treeview(
table_frame, columns=columns, show="headings", selectmode="browse"
)
# 設定欄位標題與寬度
self.tree.heading("id", text="編號")
self.tree.heading("name", text="姓名")
self.tree.heading("phone", text="電話")
self.tree.heading("group", text="群組")
self.tree.heading("email", text="Email")
self.tree.heading("note", text="備註")
self.tree.column("id", width=50, anchor="center")
self.tree.column("name", width=100, anchor="center")
self.tree.column("phone", width=120, anchor="center")
self.tree.column("group", width=80, anchor="center")
self.tree.column("email", width=180, anchor="w")
self.tree.column("note", width=200, anchor="w")
# 捲動軸
scrollbar = ttk.Scrollbar(
table_frame, orient="vertical", command=self.tree.yview
)
self.tree.configure(yscrollcommand=scrollbar.set)
self.tree.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# 綁定點擊事件
self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)
def load_data(self, query=None, params=()):
"""載入資料至表格"""
for row in self.tree.get_children():
self.tree.delete(row)
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
if query:
cursor.execute(query, params)
else:
cursor.execute(
"SELECT id, name, phone, group_name, email, note FROM contacts ORDER BY id DESC"
)
for row in cursor.fetchall():
self.tree.insert("", "end", values=row)
def add_contact(self):
"""新增聯絡人"""
name = self.name_var.get().strip()
phone = self.phone_var.get().strip()
if not name or not phone:
messagebox.showwarning("欄位缺漏", "「姓名」與「電話」為必填欄位!")
return
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"INSERT INTO contacts (name, phone, email, group_name, note) VALUES (?, ?, ?, ?, ?)",
(
name,
phone,
self.email_var.get().strip(),
self.group_var.get().strip(),
self.note_var.get().strip(),
),
)
conn.commit()
self.clear_fields()
self.load_data()
messagebox.showinfo("成功", f"已新增聯絡人:{name}")
def update_contact(self):
"""修改選取的聯絡人"""
if not self.selected_id:
messagebox.showwarning("未選取", "請先從下方列表點選要修改的聯絡人!")
return
name = self.name_var.get().strip()
phone = self.phone_var.get().strip()
if not name or not phone:
messagebox.showwarning("欄位缺漏", "「姓名」與「電話」為必填欄位!")
return
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"""UPDATE contacts
SET name=?, phone=?, email=?, group_name=?, note=?
WHERE id=?""",
(
name,
phone,
self.email_var.get().strip(),
self.group_var.get().strip(),
self.note_var.get().strip(),
self.selected_id,
),
)
conn.commit()
self.clear_fields()
self.load_data()
messagebox.showinfo("成功", "資料已更新!")
def delete_contact(self):
"""刪除選取的聯絡人"""
if not self.selected_id:
messagebox.showwarning("未選取", "請先從下方列表點選要刪除的聯絡人!")
return
if messagebox.askyesno(
"確認刪除", f"確定要刪除「{self.name_var.get()}」的資料嗎?"
):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"DELETE FROM contacts WHERE id=?", (self.selected_id,)
)
conn.commit()
self.clear_fields()
self.load_data()
def search_contact(self):
"""關鍵字搜尋(支援姓名、電話、群組、備註)"""
keyword = f"%{self.search_var.get().strip()}%"
query = """
SELECT id, name, phone, group_name, email, note
FROM contacts
WHERE name LIKE ? OR phone LIKE ? OR group_name LIKE ? OR note LIKE ?
ORDER BY id DESC
"""
self.load_data(query, (keyword, keyword, keyword, keyword))
def on_tree_select(self, event):
"""點選列表項目時,將資料帶入上方輸入框"""
selected = self.tree.selection()
if selected:
values = self.tree.item(selected[0], "values")
self.selected_id = values[0]
self.name_var.set(values[1])
self.phone_var.set(values[2])
self.group_var.set(values[3])
self.email_var.set(values[4])
self.note_var.set(values[5])
def clear_fields(self):
"""清空輸入欄位"""
self.selected_id = None
self.name_var.set("")
self.phone_var.set("")
self.group_var.set("一般")
self.email_var.set("")
self.note_var.set("")
if self.tree.selection():
self.tree.selection_remove(self.tree.selection())
def export_csv(self):
"""匯出成 Excel 可開啟的 UTF-8-SIG CSV 檔"""
file_path = filedialog.asksaveasfilename(
defaultextension=".csv",
filetypes=[("CSV 檔案", "*.csv")],
initialfile="通訊錄備份.csv",
)
if not file_path:
return
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
cursor.execute(
"SELECT id, name, phone, group_name, email, note FROM contacts"
)
rows = cursor.fetchall()
with open(file_path, "w", newline="", encoding="utf-8-sig") as f:
writer = csv.writer(f)
writer.writerow(["編號", "姓名", "電話", "群組", "Email", "備註"])
writer.writerows(rows)
messagebox.showinfo("匯出完成", f"已成功匯出 {len(rows)} 筆資料!")
if __name__ == "__main__":
root = tk.Tk()
app = AddressBookApp(root)
root.mainloop()
功能亮點
即時資料庫儲存:所有資料直接寫入同目錄下的
contacts.db(SQLite),重開程式資料不會遺失。一鍵點選編輯:在下方表格點選任一聯絡人,資料會自動帶入上方表單,方便直接修改或刪除。
支援 Excel 匯出:匯出 CSV 時已採用
utf-8-sig編碼,用 Windows 的 Excel 直接雙擊開啟不會出現中文亂碼。

