IT243 Programming with Python

Programming with PythonUnit 107 min read

Web & GUI Programming: Tkinter, Web Basics, APIs, Flask, HTML/CSS

Unit 10 of Programming with Python covers building user interfaces (GUIs) with Tkinter, creating web pages with HTML/CSS, interacting with web APIs, and developing lightweight web apps using Flask—essential skills for modern software development.

Core Concepts & Definitions

1. Graphical User Interfaces (GUIs)

A GUI is a visual way for users to interact with software using elements like buttons, text boxes, and menus instead of typing commands. Python’s Tkinter is a built-in library for creating GUIs.

Why Use GUIs?

  • User-friendly: No need to memorize commands.
  • Visual feedback: Immediate responses (e.g., button clicks).
  • Widely used: Apps like Khalti’s payment interface or eSewa’s login page rely on GUIs.

Tkinter Widgets (Key Components)

Widget Type Purpose Example in Tkinter
Label Displays text/images Label(text="Hello")
Button Triggers actions on click Button(text="Submit")
Entry Single-line text input Entry()
Text Multi-line text input/output Text(height=5, width=30)
Checkbutton Toggle options (on/off) Checkbutton(text="Agree")
Radiobutton Single-choice selection Radiobutton(text="Male")
Listbox Dropdown list of items Listbox()

2. Tkinter Basics: Building a Simple Calculator

Step-by-Step Code Example

import tkinter as tk

def calculate():
    num1 = float(entry_num1.get())
    num2 = float(entry_num2.get())
    result = num1 + num2
    label_result.config(text=f"Result: {result}")

# Create main window
root = tk.Tk()
root.title("Simple Calculator")

# Widgets
label_num1 = tk.Label(root, text="Enter first number:")
label_num2 = tk.Label(root, text="Enter second number:")
entry_num1 = tk.Entry(root)
entry_num2 = tk.Entry(root)
button_calc = tk.Button(root, text="Add", command=calculate)
label_result = tk.Label(root, text="Result: ")

# Layout (Grid)
label_num1.grid(row=0, column=0)
entry_num1.grid(row=0, column=1)
label_num2.grid(row=1, column=0)
entry_num2.grid(row=1, column=1)
button_calc.grid(row=2, column=0, columnspan=2)
label_result.grid(row=3, column=0, columnspan=2)

root.mainloop()

State After Each Step (Visual Trace)

flowchart TD
    A["Step 1: Import Tkinter"] --> B["Step 2: Define `calculate()` function"]
    B --> C["Step 3: Create `root` window"]
    C --> D["Step 4: Add widgets (labels, entries, button)"]
    D --> E["Step 5: Arrange widgets using `.grid()`"]
    E --> F["Step 6: Run `root.mainloop()`"]

Output GUI Preview



3. Web Programming Basics

A. HTML & CSS: Structure and Styling

  • HTML (HyperText Markup Language): Defines the structure of a webpage (e.g., headings, paragraphs, links).
  • CSS (Cascading Style Sheets): Controls the appearance (colors, fonts, layouts).

Example: A Basic HTML Page with CSS

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial; background-color: #f0f0f0; }
        h1 { color: blue; }
        .button { background: green; color: white; padding: 10px; }
    </style>
</head>
<body>
    <h1>Welcome to My Webpage</h1>
    <button class="button">Click Me</button>
</body>
</html>

How It Renders



B. Web APIs: Fetching Data from the Internet

An API (Application Programming Interface) lets programs communicate. For example:

  • Nepal’s NTC API: Fetches bus schedules.
  • Google Maps API: Provides location data.
  • WhatsApp Business API: Sends automated messages.

Example: Fetching Data from a Public API (JSONPlaceholder)

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json()
print(f"Title: {data['title']}")
print(f"Body: {data['body']}")

Output:

Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
Body:quia et suscipit...

State After API Call

sequenceDiagram
    participant User
    participant PythonScript
    participant APIServer
    User->>PythonScript: Requests data
    PythonScript->>APIServer: GET /posts/1
    APIServer-->>PythonScript: Returns JSON
    PythonScript->>User: Displays title/body

4. Flask: Building a Simple Web App

Flask is a micro web framework for Python. It lets you create web pages dynamically.

Example: A "Hello, User!" Web App

from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def home():
    return "Welcome to the Home Page!"

@app.route("/greet", methods=["GET", "POST"])
def greet():
    name = request.args.get("name", "Guest")
    return f"Hello, {name}!"

if __name__ == "__main__":
    app.run(debug=True)

How It Works

  1. @app.route("/"): Defines the homepage.
  2. @app.route("/greet"): Handles /greet?name=John requests.
  3. app.run(): Starts the server (accessible at http://127.0.0.1:5000).

State After Running the App

flowchart TD
    A["User opens browser"] --> B["Types `http://127.0.0.1:5000/greet?name=Alice`"]
    B --> C["Flask receives request"]
    C --> D["Extracts `name=Alice` from URL"]
    D --> E["Returns `Hello, Alice!`"]

## In the Real World

  1. eSewa’s Payment GUI

    • Uses Tkinter-like frameworks (or web GUIs) to let users input payment details securely.
    • APIs connect to banks (e.g., NMB, Global IME) to verify transactions.
  2. Pathao’s Ride Booking

    • Flask/Django (Python web frameworks) handle ride requests.
    • Google Maps API fetches real-time traffic data to estimate arrival times.
  3. Nepal Stock Exchange (NEPSE) Dashboard

    • HTML/CSS displays stock prices in a user-friendly layout.
    • Web APIs pull live data from NEPSE’s servers.

## Exam Tips

  1. Tkinter Questions:

    • Expect widget creation (e.g., Button, Entry) and layout methods (.grid(), .pack()).
    • Trace the GUI state after each operation (e.g., button click).
  2. HTML/CSS:

    • Know the difference between <div>, <span>, <p>, and <button>.
    • CSS selectors (e.g., .class, #id) are often tested.
  3. APIs & Flask:

    • requests.get() vs. requests.post(): When to use each.
    • Flask routes: @app.route() with methods=["GET", "POST"].
  4. Common Pitfalls:

    • Forgetting root.mainloop() in Tkinter → GUI won’t appear.
    • Not handling API errors (e.g., response.status_code).

## Practice Problems

  1. Tkinter:

    • Build a login form with Entry for username/password and a Button to submit.
  2. HTML/CSS:

    • Create a responsive navbar that changes color on hover.
  3. Flask:

    • Extend the greet app to store names in a list and display all previous greetings.
  4. APIs:


## Summary Table: GUI vs. Web Development

Feature Tkinter (GUI) Flask (Web) HTML/CSS (Web)
Purpose Desktop apps Dynamic web pages Static web structure
Language Python Python HTML/CSS/JavaScript
Example Use Calculator, Editor Blog, E-commerce Company website
Key Libraries tkinter, PyQt Flask, Django Bootstrap, Tailwind
Data Handling Local variables APIs, Databases Static files

Based on the TU BIM syllabus for Programming with Python (IT243), unit 10.

Discussion

Loading…