Programming with PythonUnit 1012 min read
Web & GUI Programming: Tkinter, Web Basics, APIs, Flask, HTML/CSS
Unit 10 of Programming with Python covers building interactive user interfaces (GUIs) with Tkinter, creating web pages with HTML/CSS, connecting to web APIs, and developing lightweight web apps with Flask—essential skills for modern software development.
TAKEAWAYS:
- Tkinter lets you create desktop GUIs with widgets like buttons, labels, and frames using Python.
- HTML/CSS define the structure and style of web pages, while JavaScript adds interactivity.
- REST APIs allow Python programs to fetch or send data to web services (e.g., weather APIs, eSewa transactions).
- Flask is a lightweight Python framework for building web backends that serve HTML or JSON.
- Event-driven programming handles user interactions (e.g., button clicks) via callbacks.
- Security in web apps requires input validation, sanitization, and protection against SQL injection/XSS.
1. Introduction to GUI Programming with Tkinter
Graphical User Interfaces (GUIs) make software intuitive. Tkinter is Python’s standard GUI library, built on Tcl/Tk. It provides widgets (buttons, text boxes, etc.) and layout managers (pack, grid, place).
flowchart TD
A["User Enters 5"] --> B["User Enters 3"]
B --> C["Click Add"]
C --> D["Calculate: 5 + 3"]
D --> E["Update Label: 'Result: 8.0'"]Event-driven flow in Tkinter calculator exampleKey Widgets and Layouts
classDiagram
class Tk {
+mainloop()
}
class Frame {
+pack()
+grid()
+place()
}
class Label {
+text="Text"
+font="Arial 12"
}
class Button {
+text="Click"
+command=callback
}
Tk <|-- Frame
Frame <|-- Label
Frame <|-- ButtonExample: A Simple Calculator GUI
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}")
root = tk.Tk()
root.title("Calculator")
label_num1 = tk.Label(root, text="Enter first number:")
label_num1.pack()
entry_num1 = tk.Entry(root)
entry_num1.pack()
label_num2 = tk.Label(root, text="Enter second number:")
label_num2.pack()
entry_num2 = tk.Entry(root)
entry_num2.pack()
button_calc = tk.Button(root, text="Add", command=calculate)
button_calc.pack()
label_result = tk.Label(root, text="Result: ")
label_result.pack()
root.mainloop()
Trace Table (State After Each Step):
| Step | entry_num1 Value |
entry_num2 Value |
label_result Text |
|---|---|---|---|
| Initial | "" | "" | "Result: " |
| User enters | "5" | "3" | "Result: " |
| Click Add | "5" | "3" | "Result: 8.0" |
Advantages of Tkinter:
- Easy to learn (built into Python).
- Cross-platform (works on Windows, macOS, Linux).
- Suitable for small to medium desktop apps.
Disadvantages:
- Limited modern aesthetics (compared to Qt or PyQt).
- No built-in support for complex animations.
2. Web Basics: HTML, CSS, and JavaScript
Web pages are built with three core technologies:
- HTML (HyperText Markup Language): Defines structure (e.g., headings, paragraphs).
- CSS (Cascading Style Sheets): Controls styling (colors, fonts, layouts).
- JavaScript: Adds interactivity (e.g., form validation, dynamic content).
Example: A Simple HTML Page with CSS Styling
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Arial; background-color: #f0f0f0; }
h1 { color: #333; text-align: center; }
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Welcome to My Web Page</h1>
<button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>
Visual: HTML Document Structure
Key Concepts:
- DOM (Document Object Model): JavaScript manipulates HTML/CSS dynamically.
- Event Listeners: Trigger actions (e.g.,
onclick,onload). - Responsive Design: CSS frameworks like Bootstrap help adapt layouts to mobile/desktop.
3. Working with Web APIs
An API (Application Programming Interface) lets programs communicate. REST APIs use HTTP methods (GET, POST, PUT, DELETE) to exchange data in JSON or XML format.
Example: Fetching Weather Data from OpenWeatherMap API
import requests
api_key = "YOUR_API_KEY"
city = "Kathmandu"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
data = response.json()
print(f"Temperature: {data['main']['temp']} Kelvin")
print(f"Weather: {data['weather'][0]['description']}")
Trace Table (API Response Handling):
| Step | response.status_code |
data['main']['temp'] |
data['weather'][0]['description'] |
|---|---|---|---|
| Successful Request | 200 | 298.15 | "clear sky" |
| Invalid City | 404 | Error | Error |
Real-World Example: eSewa API eSewa’s API allows merchants to:
- Check transaction status via
GET /api/transaction/{id}. - Process payments using
POST /api/paymentwith JSON payloads like:{ "amount": 500, "phone": "98XXXXXXXX", "product": "Electricity" }
Security Note: Always validate inputs and use HTTPS to prevent man-in-the-middle attacks.
4. Building Web Apps with Flask
Flask is a micro web framework for Python. It routes URLs to functions and renders templates (HTML files with dynamic content).
Example: A Flask App for a Simple Blog
from flask import Flask, render_template, request
app = Flask(__name__)
posts = [
{"id": 1, "title": "First Post", "content": "Hello World!"},
{"id": 2, "title": "Second Post", "content": "Flask is awesome!"}
]
@app.route("/")
def home():
return render_template("index.html", posts=posts)
@app.route("/post/<int:post_id>")
def show_post(post_id):
post = next((p for p in posts if p["id"] == post_id), None)
return render_template("post.html", post=post)
if __name__ == "__main__":
app.run(debug=True)
Directory Structure:
my_flask_app/
│── app.py
│── templates/
│ ├── index.html
│ └── post.html
Visual: Flask Request Flow
sequenceDiagram
participant User
participant Browser
participant Flask
participant Template
User->>Browser: Requests "/post/1"
Browser->>Flask: GET /post/1
Flask->>Flask: Finds post_id=1
Flask->>Template: Renders post.html
Template-->>Browser: HTML with post data
Browser->>User: Displays postKey Flask Features:
- Routing:
@app.route("/path")maps URLs to functions. - Templates: Use
{{ variable }}for dynamic content in HTML. - Forms: Handle
POSTdata withrequest.form.
5. Real-World Applications
In the Real World
eSewa (Nepal)
- APIs: Uses REST APIs for mobile payments (e.g.,
POST /api/paymentto process transactions). - Flask/Python: Likely powers backend services for fraud detection and user authentication.
- APIs: Uses REST APIs for mobile payments (e.g.,
Pathao (Ride-Hailing App)
- GUI: Tkinter-like tools may be used in internal admin dashboards.
- Web APIs: Drivers fetch ride requests via
GET /api/ride-requests.
Ncell’s MyNcell App
- Flask: Backend handles SMS API integrations (e.g.,
POST /api/sms). - HTML/CSS: Web portal for checking bills uses responsive design.
- Flask: Backend handles SMS API integrations (e.g.,
Daraz (E-Commerce)
- JavaScript: Dynamic product filters (e.g., sorting by price).
- APIs:
GET /api/products?category=electronicsfetches inventory.
Worked Example: Kathmandu Traffic Route Finder
Problem: Simulate a Flask app that suggests the fastest route using a mock API.
from flask import Flask, request, jsonify
app = Flask(__name__)
# Mock traffic data (1=slow, 5=fast)
traffic_data = {
"Thamel to Kantipath": {"route": "Ring Road", "speed": 3},
"Kathmandu to Bhaktapur": {"route": "Prithvi Highway", "speed": 4}
}
@app.route("/route", methods=["GET"])
def get_route():
origin = request.args.get("origin")
destination = request.args.get("destination")
route = traffic_data.get(f"{origin} to {destination}", None)
if route:
return jsonify({"route": route["route"], "speed": route["speed"]})
return jsonify({"error": "Route not found"}), 404
if __name__ == "__main__":
app.run()
Test Case:
- Request:
GET /route?origin=Thamel&destination=Kantipath - Response:
{"route": "Ring Road", "speed": 3}
6. Exam Tips
Tkinter Questions:
- Know how to create a window (
tk.Tk()), add widgets (pack(),grid()), and bind events (command=). - Common Pitfall: Forgetting
root.mainloop()—the app won’t display without it!
- Know how to create a window (
HTML/CSS:
- Memorize basic tags (
<div>,<span>,<form>) and CSS properties (display: flex,margin). - Exam Trick: Describe how to center a
<button>using CSS:button { display: block; margin: 0 auto; }
- Memorize basic tags (
Flask:
- Understand the difference between
GET(retrieve data) andPOST(send data). - Code Snippet to Recall:
@app.route("/login", methods=["POST"]) def login(): username = request.form["username"] return f"Welcome, {username}!"
- Understand the difference between
APIs:
- Explain the HTTP status codes (e.g.,
200 OK,404 Not Found). - Example Question: "How would you fetch user data from a REST API?"
Answer:
import requests response = requests.get("https://api.example.com/users/1") if response.status_code == 200: user = response.json()
- Explain the HTTP status codes (e.g.,
Security:
- Always mention input validation and SQL injection prevention (use parameterized queries).
- Example: Sanitize user input in Flask:
from flask import escape user_input = request.form["comment"] safe_input = escape(user_input) # Prevents XSS
Summary Table: GUI vs. Web Technologies
| Feature | Tkinter | HTML/CSS/JavaScript | Flask |
|---|---|---|---|
| Purpose | Desktop GUIs | Web pages | Web backends |
| Language | Python | HTML/CSS/JS | Python |
| Example Use Case | Calculator app | eSewa’s web portal | Daraz’s order processing |
| Key Components | Widgets (Button, Label) | <div>, class, onclick |
Routes (@app.route), Templates |
| Data Handling | Local variables | JSON via APIs | SQL databases or APIs |
| Deployment | Standalone .py file |
Hosted on a web server | Requires a server (e.g., Gunicorn) |
In the real world
- eSewa: Uses REST APIs (POST/PUT requests with JSON payloads) for payment processing and transaction status checks, demonstrating how Python programs interact with web services via HTTP methods.
- Pathao: Implements event-driven programming in its mobile app (e.g., button clicks triggering ride requests or payment confirmations) using frameworks like Flutter (similar principles apply in Tkinter).
- Nepal Rastra Bank’s API: Banks use Flask-like backends (often Django/Flask) to serve real-time account balance data (JSON responses) to mobile banking apps like Ncell Money or Khalti, showcasing web app architecture.
Based on the TU BITM syllabus for Programming with Python (IT243), unit 10.
Discussion
Loading…