Thursday, 29 May 2025

Unit 6: Database and GUI Programming



Unit 6: Database and GUI Programming

[Total Hours: 12]

Database and GUI programming are essential components of modern application development. This unit introduces how to handle data using a lightweight database system (SQLite) and build user interfaces using Python’s tkinter module. These skills allow the creation of interactive and data-driven desktop applications.


6.1 Opening and Closing Database Connection with SQLite

SQLite is a lightweight, serverless database engine that is integrated with Python via the sqlite3 module. Before any operation (read, insert, delete), we must connect to the database using:

import sqlite3
conn = sqlite3.connect('students.db')

This establishes a connection. After completing operations, it is important to close the connection to free up resources:

conn.close()

6.2 Creating and Deleting Tables

Once connected to a database, SQL commands are used to create and delete tables. For example:

cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS students (id INTEGER PRIMARY KEY, name TEXT, marks INTEGER)''')
conn.commit()

To delete a table:

cursor.execute("DROP TABLE IF EXISTS students")

6.3 Adding Data to a Table

Inserting data into the table is done using the INSERT command:

cursor.execute("INSERT INTO students (name, marks) VALUES (?, ?)", ('Alice', 85))
conn.commit()

Using placeholders (?) helps prevent SQL injection and is best practice.


6.4 CRUD Operations

CRUD stands for Create, Read, Update, and Delete — the four basic operations for managing data in a database.

  • Create: Add new records using INSERT

  • Read: Fetch data using SELECT

  • Update: Modify existing data using UPDATE

  • Delete: Remove records using DELETE

Example:

# Read
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall()

# Update
cursor.execute("UPDATE students SET marks = 90 WHERE name = 'Alice'")

# Delete
cursor.execute("DELETE FROM students WHERE name = 'Alice'")

6.5 Using the tkinter Module

The tkinter module is the standard GUI toolkit for Python. It allows developers to create windows, labels, buttons, text fields, and other widgets to interact with users.

A basic GUI window:

import tkinter as tk
window = tk.Tk()
window.title("Simple App")
window.mainloop()

6.6 Working with Widgets

Widgets are building blocks of GUIs. Common widgets include:

  • Label: Displays text

  • Button: Performs actions

  • Entry: Accepts text input

  • Radiobutton: For selecting one option from a set

  • Checkbutton: For selecting multiple options

Example:

label = tk.Label(window, text="Enter Name:")
entry = tk.Entry(window)
button = tk.Button(window, text="Submit")

Dialog boxes can be used for messages or confirmations:

from tkinter import messagebox
messagebox.showinfo("Success", "Data saved successfully!")

6.7 Organizing Widgets with Frames

Frames are containers used to organize widgets neatly:

frame = tk.Frame(window)
frame.pack()
tk.Label(frame, text="Name:").pack(side=tk.LEFT)
tk.Entry(frame).pack(side=tk.RIGHT)

Using frames helps in building complex interfaces by dividing the window into sections.


6.8 Drawing Shapes with Canvas Widget

The Canvas widget allows drawing custom graphics like lines, rectangles, circles, etc.

canvas = tk.Canvas(window, width=200, height=200)
canvas.create_rectangle(50, 50, 150, 150, fill="blue")
canvas.pack()

Canvas can also be used for:

  • Circles (via create_oval)

  • Polygons (create_polygon)

  • Text (create_text)


Performing Simple Calculations Using GUI

Applications often require input-based calculations. For instance, calculating total marks:

def calculate():
    a = int(entry1.get())
    b = int(entry2.get())
    result.set(a + b)

entry1 = tk.Entry(window)
entry2 = tk.Entry(window)
result = tk.StringVar()
tk.Label(window, textvariable=result).pack()
tk.Button(window, text="Add", command=calculate).pack()

๐Ÿงช Practical Work

✔️ 1. Establish Database Connection and Create/Delete Table

conn = sqlite3.connect('data.db')
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, name TEXT)")
conn.commit()
conn.close()

✔️ 2. Store and Manipulate Data

cursor.execute("INSERT INTO users VALUES (1, 'John')")
cursor.execute("UPDATE users SET name='Jane' WHERE id=1")
cursor.execute("DELETE FROM users WHERE id=1")

✔️ 3. Perform CRUD Operation

# Complete implementation combining insert, read, update, and delete

✔️ 4. Create GUI with Widgets

label = tk.Label(window, text="Name:")
entry = tk.Entry(window)
check = tk.Checkbutton(window, text="Subscribe")
radio = tk.Radiobutton(window, text="Option 1", value=1)

✔️ 5. Organize Widgets with Frame

frame = tk.Frame(window)
frame.pack()
tk.Label(frame, text="Enter Age:").pack(side=tk.LEFT)
tk.Entry(frame).pack(side=tk.RIGHT)

✔️ 6. Draw Geometric Shapes Using Canvas

canvas = tk.Canvas(window, width=300, height=300)
canvas.create_line(0, 0, 300, 300)
canvas.create_oval(100, 100, 200, 200)
canvas.pack()


No comments:

Post a Comment

Unit IV: Evaluation and Feedback | Teaching Method | Notes | Seven Semester | BICTE

๐Ÿ“˜ Unit IV: Evaluation and Feedback Total Time: 4 Hours ๐Ÿ”น 4.1 Assessing Student Performance with ICT ICT tools offer flexible, efficie...