0% found this document useful (0 votes)
4 views19 pages

Unit-4 (Python)

This document provides an overview of GUI programming, detailing its purpose, components, characteristics, advantages, and disadvantages, as well as various libraries available in Python for GUI development, such as Tkinter, PyQt, and Kivy. It also covers web programming concepts, including client-server architecture, HTTP requests, and the roles of frontend, backend, and databases in web applications, highlighting Python's versatility in web development. Additionally, it discusses the advantages of using Python for web programming and its applications in web scraping and automation.

Uploaded by

jkuhhhhhtt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views19 pages

Unit-4 (Python)

This document provides an overview of GUI programming, detailing its purpose, components, characteristics, advantages, and disadvantages, as well as various libraries available in Python for GUI development, such as Tkinter, PyQt, and Kivy. It also covers web programming concepts, including client-server architecture, HTTP requests, and the roles of frontend, backend, and databases in web applications, highlighting Python's versatility in web development. Additionally, it discusses the advantages of using Python for web programming and its applications in web scraping and automation.

Uploaded by

jkuhhhhhtt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit – 4

GUI Programming :
1. Introduction

GUI (Graphical User Interface) is a visual way for users to interact with a computer program.
Instead of typing commands in text form (like in Command Prompt), users can click buttons, select
menus, drag items, and see results immediately on the screen.

Example:

 When you use a Calculator, Paint, or File Explorer on your computer — those are GUI
applications.
You click buttons, open menus, and move windows — all actions happen through a graphical
interface.

2. Purpose of GUI

The main goal of GUI is to make interaction between the user and computer:

 Easier

 More intuitive

 Visually appealing

 Less error-prone

3. How GUI Works

GUI applications follow an Event-Driven Model.

➤ Event-driven model means:

The program waits for user actions (events) such as:

 Mouse click 🖱️

 Keyboard input ⌨️

 Window resize or close

Each of these actions triggers a function or command inside the program.

Example flow:

User clicks button → Event generated → Program handles event → Action performed
Example in Python (Tkinter):

from tkinter import *

def greet():

print("Hello!")

root = Tk()

btn = Button(root, text="Click Me", command=greet)

[Link]()

[Link]()

Here:

 The Button waits for a click event.

 When clicked, it calls the greet() function.

4. Components of a GUI

GUI applications are built from widgets (controls) — visual elements that allow user interaction.

Component Description Example

Window The main frame that holds all GUI elements App window

Label Displays text or images "Welcome!"

Button Executes an action when clicked “Submit”

Textbox / Entry Allows user input Enter name

Menu / Menu Bar Lists commands File → Save, Exit

Checkbox Select multiple options ✓ Enable sound

Radiobutton Select one option ○ Male ○ Female

Canvas Drawing area for graphics Paint app

Frame Container to group widgets Section layout


5. Characteristics of GUI

 User-friendly: Uses icons and visuals.

 Interactive: Responds to user actions.

 WYSIWYG (What You See Is What You Get): The output on the screen represents the result
directly.

 Multitasking: Multiple windows and applications can run simultaneously.

 Consistency: Common look and feel across programs.

6. Advantages of GUI

Advantages Explanation

Ease of Use No need to remember commands.

Speed of Learning Users can easily understand icons and menus.

Error Reduction Visual feedback reduces typing mistakes.

Attractive Design Colors, fonts, and images improve experience.

Multitasking Can manage several windows or tabs at once.

7. Disadvantages of GUI

Disadvantages Explanation

Resource Heavy Uses more memory and CPU than text-based systems.

Complex to Design Creating GUI requires more code and testing.

Slower for Experts Command-line can be faster for advanced users.

8. GUI in Python

Python offers several libraries to create GUI applications.

Library Description Use Case


Library Description Use Case

Tkinter Built-in Python GUI toolkit Basic desktop apps

PyQt / PySide Based on Qt framework Professional apps

Kivy Cross-platform & touch support Mobile apps

wxPython Native OS look Desktop tools

DearPyGUI Modern GPU-based GUI Dashboards, tools

9. Architecture of GUI System

A GUI system generally has three main parts:

1. Application (Frontend) – The visible interface users interact with.

2. Backend (Logic) – Processes user requests and manages data.

3. Event Handler (Middleware) – Connects GUI actions with backend functions.

10. GUI Design Principles

1. Simplicity – Keep the layout clean and minimal.

2. Consistency – Use the same colors, fonts, and button styles.

3. Feedback – Inform users about actions (e.g., pop-up message).

4. Accessibility – Ensure readability and usability for all users.

5. Responsiveness – App should react quickly to actions.

11. Real-World Examples of GUI

Application GUI Features

MS Paint Canvas, color picker, buttons

Calculator Numeric buttons, display field

Web Browser Tabs, address bar, menus

File Explorer Icons, drag-and-drop support


Tkinter :

Tkinter is the standard GUI (Graphical User Interface) library for Python.
It is built into Python, meaning you don’t need to install it separately — it comes automatically when you
install Python.

Tkinter provides tools (called widgets) like:

1. Button:
A clickable widget used to perform an action or execute a function when pressed.

2. Label:
A widget used to display text or images on the GUI window; usually for information or titles.

3. Text Box (Entry):


A widget that allows users to input single-line text data such as names or numbers.

4. Frame:
A container widget used to group and organize other widgets within a window.

5. Menu:
A list of commands or options presented in a drop-down style for user interaction.

6. Message Box:
A pop-up dialog box used to display messages, warnings, or ask questions to the user.

Why Use Tkinter?

Easy to learn — simple syntax and structure.


Lightweight — runs easily on all platforms.
Comes pre-installed with Python.
Cross-platform — works on Windows, macOS, Linux.
Event-driven — executes functions when the user interacts (e.g., clicks a button).

How Tkinter Works (Basic Concept)

Tkinter is event-driven, meaning:

 You design the GUI with widgets (like buttons, labels).

 You assign functions to respond to events (like button clicks).

 The program runs in an infinite loop waiting for events.

Flow:

Create main window → Add widgets → Define event functions → Run mainloop()

Structure of a Tkinter Program


Here’s the basic structure of any Tkinter program:

from tkinter import *

[Link] the main window

root = Tk()

[Link] widgets

label = Label(root, text="Hello, Tkinter!")

[Link]()

[Link] the application

[Link]()

Explanation:

 Tk() → Creates the main GUI window.

 Label() → Creates a label (text display).

 pack() → Places the widget on the screen.

 mainloop() → Keeps the window open and responsive

Example :

from tkinter import *

root = Tk()

[Link]("Simple App")

[Link]("300x200")

label = Label(root, text="Enter your name:", font=("Arial", 12))

[Link](pady=10)

entry = Entry(root)

[Link](pady=5)
def greet():

name = [Link]()

[Link](text=f"Hello, ,name-!")

button = Button(root, text="Greet", command=greet)

[Link](pady=10)

[Link]()

Brief Tour of Other GUIs :


Apart from Tkinter, Python supports many other GUI (Graphical User Interface) toolkits that help
developers design interactive applications.
Some popular ones are:

1. PyQt / PySide

 Based on: Qt framework (a powerful C++ library for GUI).

 Use: To create professional, advanced, and modern-looking desktop applications.

 Features:

o Supports buttons, menus, tables, dialogs, and animations.

o Can create complex interfaces easily with Qt Designer tool.

o Cross-platform – works on Windows, macOS, and Linux.

 Example apps: Many commercial apps use Qt for their GUI.

2. wxPython

 Based on: wxWidgets (C++ library).

 Use: To create native-looking applications (apps look like real Windows/macOS/Linux apps).

 Features:

o Offers native widgets – GUI looks the same as other apps on the OS.

o Cross-platform and easy to learn.

o Supports advanced UI components like notebooks, grids, and toolbars.


3. Kivy

 Use: For multitouch and mobile app development.

 Features:

o Works on Android, iOS, Windows, macOS, and Linux.

o Designed for touch-based interfaces and modern app designs.

o Good for making apps, games, and interactive systems.

 Language: Python with its own layout language (KV language).

4. PyGTK / PyGObject

 Use: To create GNOME-based applications for Linux.

 Features:

o Works with the GTK toolkit (used in Linux desktop environments).

o Provides modern widgets like buttons, trees, and combo boxes.

o Mainly used for Linux but can also run on other systems.

 Used in: Many Linux desktop utilities and tools.

5. PySimpleGUI

 Use: To make GUI programming simple and beginner-friendly.

 Features:

o Works as a wrapper around Tkinter, Qt, WxPython, or Remi.

o Lets you create GUIs with fewer lines of code.

o Easy syntax – perfect for beginners and quick prototypes.

 Example:

 import PySimpleGUI as sg

 [Link]("Hello, World!")

This one line shows a GUI message box!


Related Modules and Other GUIs
1. turtle

 Purpose:
The turtle module is a simple graphics library mainly used for teaching programming to
beginners.

 How it works:
It uses a virtual “turtle” that moves around the screen, drawing lines as it moves — based on
commands like forward(), left(), right().

 Uses:

o Drawing geometric shapes and patterns

o Learning loops and functions in Python

o Simple animations

 Example:

 import turtle

 t = [Link]()

 for i in range(4):

 [Link](100)

 [Link](90)

 [Link]()

➤ Draws a square using the turtle.

2. easygui

 Purpose:
The easygui module allows the creation of simple GUI dialogs without writing complex code.

 How it works:
It provides easy-to-use windows for input, file selection, and messages — perfect for beginners.

 Uses:

o Displaying messages (msgbox())

o Getting user input (enterbox())

o Opening file dialogs (fileopenbox())


 Example:

 import easygui

 name = [Link]("Enter your name:")

 [Link](f"Hello, ,name-!")

➤ Opens two GUI dialogs — one to ask for input and one to show a message.

3. PyGame

 Purpose:
The pygame library is used for game development and interactive graphics applications.

 How it works:
It provides modules for handling images, sounds, animations, and user input (keyboard/mouse).

 Uses:

o 2D game development

o Simulations and multimedia projects

 Example:

 import pygame

 [Link]()

 screen = [Link].set_mode((400, 300))

 [Link].set_caption("My Game")

 running = True

 while running:

 for event in [Link]():

 if [Link] == [Link]:

 running = False

 [Link]()

➤ Creates a basic game window.

4. OpenGL (PyOpenGL)
 Purpose:
The PyOpenGL library allows Python to use OpenGL, a powerful cross-platform library for 3D
graphics and visualization.

 How it works:
It gives access to GPU rendering features for drawing 3D shapes, textures, lighting, and motion.

 Uses:

o 3D modeling

o Scientific visualization

o Game and simulation graphics

 Example:
Often used with other libraries like pygame or GLUT to display 3D graphics.

5. matplotlib (with Tkinter)

 Purpose:
matplotlib is a data visualization library that can also be embedded in GUI windows using
Tkinter.

 How it works:
You can display plots and charts (line, bar, pie, etc.) directly inside a Tkinter window.

 Uses:

o Scientific and business data visualization

o Dashboards and analysis tools

 Example:

 import [Link] as plt

 from tkinter import Tk

 from [Link].backend_tkagg import FigureCanvasTkAgg

 root = Tk()

 fig, ax = [Link]()

 [Link](*1, 2, 3, 4+, *10, 20, 25, 30+)

 canvas = FigureCanvasTkAgg(fig, master=root)

 canvas.get_tk_widget().pack()

 [Link]()
 [Link]()

➤ Displays a matplotlib chart inside a Tkinter window.

Web Programming :
What is Web Programming?

Web programming (also called web development) means writing programs that allow computers and
people to communicate over the World Wide Web (WWW).

It involves developing applications that run on a web browser and are connected through the Internet.

The Web Is Based on:

 Client–Server Architecture
 HTTP (Hypertext Transfer Protocol)
 HTML, CSS, and JavaScript for user interfaces
 Databases for storing data (like PostgreSQL, MySQL, MongoDB)
 Programming languages (like Python, PHP, JavaScript) for backend logic

Client–Server Model

The web uses a Client–Server model, which defines how computers communicate:

Component Description Example

Sends requests to the server (usually a browser like Chrome,


Client User visiting a website
Edge, etc.)

Processes the request and sends a response (like HTML page or Web server running
Server
data) Python

Example Flow:

1. User types a URL like [Link]


2. Browser sends an HTTP request to the web server.
3. Server processes the request (runs Python code, queries database, etc.)
4. Server sends back an HTTP response (HTML, JSON, etc.)
5. Browser displays it to the user.
HTTP Request Example

Client → Server (Request):

GET /[Link] HTTP/1.1


Host: [Link]
User-Agent: Chrome

Server → Client (Response):

HTTP/1.1 200 OK
Content-Type: text/html

<html><body><h1>Welcome!</h1></body></html>

Types of Web Programming

🔹(a) Client-Side Programming

Runs in the browser (on the user's device).

Languages & Technologies:

 HTML – Structure of webpage


 CSS – Styling and design
 JavaScript – Interactivity
 React / Angular / Vue – Advanced front-end frameworks

Example:

<h1>Welcome</h1>
<script>
alert("Hello from Client Side!");
</script>

🔹(b) Server-Side Programming

Runs on the server — generates the webpage or data dynamically before sending to the client.

Languages:

 Python �
 PHP
 [Link]
 Java
 Ruby

Example (Python):

from [Link] import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
[Link](b"<h1>Hello from Server Side!</h1>")

HTTPServer(("", 8080), MyHandler).serve_forever()

Components of a Web Application

Component Role Example

Frontend (Client-
Interface the user sees HTML, CSS, JavaScript
side)

Backend (Server- Logic, processing, and communication with


Python, Flask, Django
side) DB

Database Store data permanently MySQL, PostgreSQL, MongoDB

Apache, Nginx, Python’s


Web Server Hosts the application
[Link]

Python in Web Programming

Python can be used for all layers of web development — backend, API, automation, scraping, etc.

🔹Uses of Python:
Area Description Library/Tool

Web Frameworks Build full web apps Django, Flask, FastAPI

Web Scraping Extract info from websites BeautifulSoup, Scrapy


Area Description Library/Tool

Automation Automate browser or tasks Selenium, Requests

APIs Connect applications Flask REST API, FastAPI

Web Servers Serve pages to browsers [Link], Gunicorn

Data Handling Manage user or app data Pandas, SQLAlchemy

Advantages of Python for Web Programming


� Easy to learn and write
� Huge library support
� Cross-platform and open-source
� Integrates well with databases and APIs
� Suitable for both small and large applications
� Great for AI/ML integration in web apps

Web Surfing with Python :

Web surfing with Python refers to accessing, reading, and interacting with web pages
automatically using Python programs instead of a browser. It allows you to fetch data from
websites, send information to servers, and automate online tasks.

Python provides several libraries for this purpose:

1. urllib module – a built-in library for sending HTTP requests and receiving responses.
Example:
2. from urllib import request
3. response = [Link]("[Link]
4. print([Link]().decode())

This downloads and displays the HTML of a web page.

5. requests library – a more powerful and user-friendly library for web access.
Example:
6. import requests
7. response = [Link]("[Link]
8. print([Link])

It’s widely used for working with APIs and websites.

9. BeautifulSoup (from bs4) – used to parse and extract data (like headlines, links, or
prices) from HTML pages.
10. Selenium – used to automate browsers (like Chrome or Firefox) and simulate real user
actions such as clicking buttons, logging in, or filling forms.

�Uses of Web Surfing with Python:

 Web scraping (extracting data from websites).


 Automated form submission.
 Collecting data from multiple websites.
 Testing web applications automatically.

In short, web surfing with Python is the process of programmatically browsing,


downloading, and interacting with web content using Python tools and libraries.

Creating Simple Web Clients :

A web client is a program that sends requests to a web server and receives responses — similar
to how a browser works.
In Python, you can create simple web clients to fetch web pages or data from APIs.

Common libraries:

 [Link] → Built-in module for sending requests.


 requests → Popular library for easier HTTP communication.

Example using requests:

import requests
response = [Link]("[Link]
print(response.status_code) # Shows status like 200 (OK)
print([Link]) # Shows webpage content

Key functions of a simple web client:

 Send GET requests (to fetch data)


 Send POST requests (to send data)
 Handle HTTP status codes
 Display or store server responses

Simple clients are mainly used for testing APIs, downloading data, or basic web scraping.
Advanced Web Clients :

Advanced web clients are more powerful — they handle cookies, sessions, authentication,
headers, and automation.
They can simulate a real browser and interact dynamically with web pages.

Libraries used:

 requests (with sessions)


 [Link] (for low-level HTTP handling)
 Selenium (for browser automation)
 aiohttp (for asynchronous/multiple requests)

Example using [Link]:

import requests

session = [Link]()
[Link]("[Link]
response = [Link]("[Link]
data={"user":"abc","pass":"123"})
print([Link])

Advanced client features:

 Maintain sessions (like staying logged in)


 Manage cookies and headers
 Handle authentication (Basic, OAuth, JWT)
 Perform asynchronous requests for speed
 Automate browsing and data extraction (e.g., Selenium)

CGI – Helping Servers Process Client Data

CGI (Common Gateway Interface) is a standard method that allows web servers to communicate with
external programs (like Python scripts) to process user input and generate dynamic web pages.

When a user fills a web form and submits it:

 The data goes to the web server.


 The server passes that data to a CGI script (e.g., written in Python).
 The CGI script processes it (e.g., saves to database, performs calculations).
 The script sends the result (HTML) back to the browser.

Example:
#!/usr/bin/python3
import cgi

print("Content-type:text/html\n")
form = [Link]()
name = [Link]("name")
print(f"<h2>Hello {name}</h2>")

This CGI script reads user input (name) from a form and displays a response.

� In short: CGI helps the web server run Python code to handle form data and create dynamic web
content.

Building a CGI Application

A CGI application is a full working system that uses CGI scripts to handle web requests.

Steps to build one:

1. Create an HTML form to collect user data.


2. Write a Python CGI script to process that data.
3. Store the script in the server’s cgi-bin directory.
4. Configure the web server to allow CGI execution.
5. Return an HTML response to the user.

Example flow:
HTML form → submit → Python script → process data → send response

Use cases:

 Online forms
 Feedback or contact pages
 Simple web applications

Advanced CGI

Advanced CGI extends basic CGI by adding features like:

 Database connectivity (e.g., using MySQL, PostgreSQL)


 Session management (tracking users)
 Error handling and logging
 Template systems to separate HTML and Python code
 Security features (input validation to prevent attacks)
Example: A CGI script that connects to a database to show user details.

Advanced CGI applications are more interactive and secure, often serving as the foundation for early
dynamic websites before frameworks like Django or Flask were developed.

Web (HTTP) Servers

A web server is software that delivers web pages to users. It receives HTTP requests from clients
(browsers or Python scripts) and sends responses (HTML, data, files).

Popular web servers:

 Apache
 Nginx
 Microsoft IIS

How it works:

1. Client sends a request (e.g., GET /[Link]).


2. Server processes it.
3. If it’s a static page → sends HTML file.
4. If it’s dynamic → calls a CGI or backend script.
5. Sends back the response to the browser.

In Python: You can create a simple web server easily:

from [Link] import HTTPServer, CGIHTTPRequestHandler

server = HTTPServer(("", 8080), CGIHTTPRequestHandler)


print("Server running on port 8080...")
server.serve_forever()

You might also like