الدرس 59 ربط برنامج Tkinter بقاعدة بيانات SQLite

ربط برنامج Tkinter بقاعدة بيانات SQLite – مثال عملي (إضافة، عرض، تعديل، حذف)

في هذا الدرس سنتعلم كيفية:

  • إنشاء قاعدة بيانات SQLite وربطها مع واجهة Tkinter.
  • إدخال بيانات (اسم - عمر).
  • عرض البيانات في قائمة.
  • تعديل أو حذف السجلات.
الدرس 59 ربط برنامج Tkinter بقاعدة بيانات SQLite

🧱 الخطوات:

  1. استخدام مكتبة sqlite3 لإنشاء وربط قاعدة البيانات.
  2. استخدام Entry و Button لإدخال البيانات.
  3. استخدام Listbox لعرض البيانات.
  4. إضافة وظائف التعديل والحذف.

🧪 الكود الكامل:

import tkinter as tk
import sqlite3

# إنشاء قاعدة البيانات
conn = sqlite3.connect("users.db")
cursor = conn.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER NOT NULL)""")
conn.commit()

# دوال العمليات
def insert_user():
    name = entry_name.get()
    age = entry_age.get()
    if name and age:
        cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
        conn.commit()
        entry_name.delete(0, tk.END)
        entry_age.delete(0, tk.END)
        refresh_list()

def refresh_list():
    listbox.delete(0, tk.END)
    cursor.execute("SELECT * FROM users")
    for user in cursor.fetchall():
        listbox.insert(tk.END, f"{user[0]} - {user[1]} ({user[2]} سنة)")

def delete_user():
    selection = listbox.curselection()
    if selection:
        selected = listbox.get(selection[0])
        user_id = selected.split(" - ")[0]
        cursor.execute("DELETE FROM users WHERE id=?", (user_id,))
        conn.commit()
        refresh_list()

def update_user():
    selection = listbox.curselection()
    if selection:
        selected = listbox.get(selection[0])
        user_id = selected.split(" - ")[0]
        new_name = entry_name.get()
        new_age = entry_age.get()
        if new_name and new_age:
            cursor.execute("UPDATE users SET name=?, age=? WHERE id=?", (new_name, new_age, user_id))
            conn.commit()
            entry_name.delete(0, tk.END)
            entry_age.delete(0, tk.END)
            refresh_list()

# تصميم واجهة المستخدم
root = tk.Tk()
root.title("إدارة المستخدمين")

tk.Label(root, text="الاسم:").grid(row=0, column=0)
entry_name = tk.Entry(root)
entry_name.grid(row=0, column=1)

tk.Label(root, text="العمر:").grid(row=1, column=0)
entry_age = tk.Entry(root)
entry_age.grid(row=1, column=1)

tk.Button(root, text="إضافة", command=insert_user).grid(row=2, column=0)
tk.Button(root, text="تعديل", command=update_user).grid(row=2, column=1)
tk.Button(root, text="حذف", command=delete_user).grid(row=2, column=2)

listbox = tk.Listbox(root, width=50)
listbox.grid(row=3, column=0, columnspan=3)

refresh_list()

root.mainloop()

✅ ماذا تعلمنا؟

  • ربط SQLite مع Tkinter.
  • حفظ البيانات واسترجاعها.
  • التفاعل مع قاعدة البيانات: إدخال، تعديل، حذف، عرض.


🎯 التمرين:

أنشئ برنامجًا باستخدام Tkinter و SQLite لإدارة قائمة كتب تحتوي على:

  • عنوان الكتاب
  • اسم المؤلف

المطلوب:

  1. إدخال عنوان ومؤلف الكتاب.
  2. عرض جميع الكتب في Listbox.
  3. زر إضافة لإدخال كتاب جديد.
  4. زر حذف لحذف الكتاب المحدد.

✅ الحل الكامل:

import tkinter as tk
import sqlite3

# إنشاء قاعدة بيانات الكتب
conn = sqlite3.connect("books.db")
cursor = conn.cursor()
cursor.execute("""
    CREATE TABLE IF NOT EXISTS books (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        author TEXT NOT NULL
    )
""")
conn.commit()

# دوال العمليات
def add_book():
    title = entry_title.get()
    author = entry_author.get()
    if title and author:
        cursor.execute("INSERT INTO books (title, author) VALUES (?, ?)", (title, author))
        conn.commit()
        entry_title.delete(0, tk.END)
        entry_author.delete(0, tk.END)
        refresh_books()

def refresh_books():
    listbox.delete(0, tk.END)
    cursor.execute("SELECT * FROM books")
    for book in cursor.fetchall():
        listbox.insert(tk.END, f"{book[0]} - {book[1]} by {book[2]}")

def delete_book():
    selection = listbox.curselection()
    if selection:
        selected = listbox.get(selection[0])
        book_id = selected.split(" - ")[0]
        cursor.execute("DELETE FROM books WHERE id=?", (book_id,))
        conn.commit()
        refresh_books()

# واجهة المستخدم
root = tk.Tk()
root.title("مكتبة الكتب")

tk.Label(root, text="عنوان الكتاب:").grid(row=0, column=0)
entry_title = tk.Entry(root, width=30)
entry_title.grid(row=0, column=1)

tk.Label(root, text="اسم المؤلف:").grid(row=1, column=0)
entry_author = tk.Entry(root, width=30)
entry_author.grid(row=1, column=1)

tk.Button(root, text="إضافة كتاب", command=add_book).grid(row=2, column=0, pady=5)
tk.Button(root, text="حذف كتاب", command=delete_book).grid(row=2, column=1, pady=5)

listbox = tk.Listbox(root, width=50)
listbox.grid(row=3, column=0, columnspan=2, pady=10)

refresh_books()

root.mainloop()

📌 نصيحة:

إذا أردت تطوير التمرين، يمكنك لاحقًا:

  • إضافة زر لتعديل بيانات كتاب.
  • البحث في القائمة باستخدام عنوان أو مؤلف.
  • عرض عدد الكتب في المكتبة.

تعليقات