0% found this document useful (0 votes)
3 views37 pages

Unit5 Notes

This document covers Python programming concepts related to Graphical User Interfaces (GUIs), including the differences between Command-Line Interfaces (CLIs) and GUIs, event-driven programming, and the tkinter module for creating GUI applications. It provides examples of various widgets such as labels, buttons, and entry fields, along with their syntax and usage. Additionally, it discusses the use of dialogs for user interaction and includes sample code for creating simple GUI applications.
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)
3 views37 pages

Unit5 Notes

This document covers Python programming concepts related to Graphical User Interfaces (GUIs), including the differences between Command-Line Interfaces (CLIs) and GUIs, event-driven programming, and the tkinter module for creating GUI applications. It provides examples of various widgets such as labels, buttons, and entry fields, along with their syntax and usage. Additionally, it discusses the use of dialogs for user interaction and includes sample code for creating simple GUI applications.
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

CSE3011 – Python Programming

UNIT 5
GUI, Multithreading, Networks & Web Programming
5.1 Graphical User Interfaces (GUI)
A Graphical User Interface (GUI) is a type of user interface that allows users to interact with a
computer program through graphical elements such as windows, buttons, menus, icons, text fields,
and dialog boxes. Unlike Command-Line Interfaces (CLI) where users type text commands, GUIs
allow interaction through visual components using a mouse, keyboard, or touch input.
The shift from CLI to GUI was one of the most significant advances in computing usability.
Applications like Microsoft Windows, macOS, web browsers, and smartphone apps all use GUIs. For
Python programmers, creating GUI applications means building software that behaves and looks like
familiar desktop applications — with windows that can be moved, resized, minimized, and closed.

5.1.1 CLI vs GUI — Comparison


Feature Command-Line Interface Graphical User Interface
(CLI) (GUI)
Interaction Text commands typed by user Mouse clicks, key presses,
touch
User expertise Requires technical knowledge Intuitive — usable by anyone
Speed Fast for experts Slower but more accessible
Feedback Text output only Visual feedback (colors,
shapes, animations)
Examples Terminal, [Link], Python Windows Explorer, browsers,
IDLE shell mobile apps
Python toolkit input(), print() tkinter, PyQt5, wxPython

5.1.2 Event-Driven Programming Paradigm


Traditional programs follow a sequential, top-to-bottom execution flow — statement after statement in
a predetermined order. GUI programs, however, are fundamentally different. They follow the event-
driven programming paradigm, where the flow of the program is determined by user actions (events)
rather than a fixed sequence.
In an event-driven program:
1. The program starts and displays the GUI window.
2. The program enters an event loop — waiting for user input.
3. When the user performs an action (clicks a button, types text, moves the mouse), an event is
generated.
4. Python calls the associated event handler (callback function) to respond to the event.
5. The event handler executes and the program returns to waiting.
6. This continues until the user closes the window.
Event Loop: The event loop is the heart of every GUI application. It is an infinite loop that
continuously checks for user events (mouse clicks, key presses, window resize, etc.) and dispatches
them to the appropriate handler functions. In tkinter, this loop is started by calling mainloop().

5.1.3 Key Concepts in Event-Driven Programming


Event: A user action that the program can detect and respond to. Examples: button click, key
press, mouse move, window close, menu selection.
Event Handler (Callback): A function that is automatically called when a specific event occurs.
Programmers bind functions to events using the command parameter or bind() method.
Widget: A visual GUI element — button, label, text field, checkbox, slider, etc. Each widget is a
Python object with attributes (size, color, font) and methods.
Window: The top-level container for a GUI application. In tkinter, created with Tk() class.
Layout Manager: A mechanism for arranging widgets inside a window. tkinter provides pack(),
grid(), and place() managers.
mainloop(): The event loop function. Keeps the window open and listening for events. Program
execution blocks here until the window is closed.

5.2 The tkinter Module


tkinter (Tk interface) is Python's standard, built-in GUI library. It provides a Python interface to the Tk
GUI toolkit, which was originally developed for the Tcl scripting language. tkinter is included in the
Python standard library — no additional installation is required.
tkinter is ideal for beginners and for creating simple to moderately complex desktop applications. For
more complex or professional applications, alternatives like PyQt5, wxPython, or Kivy are used, but
for learning GUI concepts and for academic projects, tkinter is the standard choice.

5.2.1 Setting Up tkinter


Basic tkinter structure
import tkinter as tk # Import tkinter module

# Step 1: Create the root window


root = [Link]()

# Step 2: Set window properties


[Link]('My First GUI Application')
[Link]('400x300') # width x height in pixels
[Link](bg='lightyellow')

# Step 3: Add widgets (to be covered in detail)

# Step 4: Start the event loop


[Link]()
When this program is executed, a window with the title 'My First GUI Application' appears on the
screen. The window stays open because of mainloop() — it enters the event loop and waits for user
interaction. The program terminates only when the user closes the window.

5.2.2 tkinter Widget Hierarchy


In tkinter, all GUI elements are organized in a hierarchy. The root window (Tk) is the parent of all
other widgets. Every widget must have a parent specified when created.
Category Widgets
Top-level containers Tk() — root window, Toplevel() — secondary
windows
Category Widgets
Layout containers Frame, LabelFrame
Display widgets Label, Canvas, Message, Separator
Input widgets Entry, Text, Spinbox, Scale, Scrollbar
Action widgets Button, Checkbutton, Radiobutton, Menubutton
Menu widgets Menu, OptionMenu
Dialog widgets filedialog, messagebox, colorchooser,
simpledialog

5.2.3 Creating a Simple GUI Window


Program 1: Hello World GUI
import tkinter as tk

root = [Link]()
[Link]('Hello GUI')
[Link]('300x200')

# Create a Label widget


label = [Link](root, text='Hello, World!',
font=('Arial', 24, 'bold'),
fg='blue', bg='lightyellow')
[Link](pady=50) # Add to window with padding

[Link]()
When executed: A 300×200 pixel window appears with the title 'Hello GUI' and a bold blue 'Hello,
World!' label centered in the window with a light yellow background.

5.3 Labels, Buttons and Event Handling

5.3.1 Label Widget


A Label widget displays static text or an image in the window. Labels are read-only — users cannot
edit them. They are used to describe other widgets, display program output, or show instructions.
Label Syntax
label = [Link](parent, option=value, ...)

Option Description Example Value


text Text to display 'Enter your name:'
font Font specification as tuple ('Arial', 14, 'bold')
fg Foreground (text) color 'red', '#FF0000'
bg Background color 'white', '#FFFFFF'
width Width in characters 20
height Height in lines 2
Option Description Example Value
anchor Text alignment inside widget 'w', 'center', 'e'
relief Border style 'flat','raised','sunken','ridge','groove'
padx Horizontal internal padding 10
pady Vertical internal padding 5
image Image to display (PhotoImage img
object)
justify Multi-line text alignment 'left','center','right'
wraplength Maximum line length before 200
wrap (pixels)

Program 2: Multiple Labels with different styles


import tkinter as tk

root = [Link]()
[Link]('Label Demo')
[Link]('350x250')

lbl1 = [Link](root, text='Simple Label',


font=('Helvetica', 14))
[Link](pady=5)

lbl2 = [Link](root, text='Styled Label',


font=('Times New Roman', 16, 'bold italic'),
fg='white', bg='darkblue',
width=20, relief='raised', pady=8)
[Link](pady=5)

lbl3 = [Link](root,
text='This is a long label that wraps automatically',
wraplength=200, justify='center',
fg='darkgreen')
[Link](pady=5)

[Link]()

5.3.2 Button Widget


A Button widget creates a clickable button. When clicked, it executes a callback function specified
through the command parameter. Buttons are the primary mechanism for triggering actions in GUI
programs.
Button Syntax
button = [Link](parent, text='Click Me', command=callback_fn)

Option Description Example


text Label on the button 'Submit', 'OK', 'Cancel'
Option Description Example
command Callback function to call on click my_function
font Font for button text ('Arial', 12, 'bold')
fg Text color 'white'
bg Background color 'blue'
width Button width in characters 15
height Button height in lines 2
state Enable/disable button 'normal','disabled','active'
relief Border style 'raised','flat','sunken'
activebackground BG color when pressed 'lightblue'
cursor Mouse cursor when hovering 'hand2'

Program 3: Button with event handling


import tkinter as tk

counter = 0

def increment():
global counter
counter += 1
count_label.config(text=f'Count: {counter}')

def reset():
global counter
counter = 0
count_label.config(text='Count: 0')

root = [Link]()
[Link]('Counter App')
[Link]('280x200')

count_label = [Link](root, text='Count: 0',


font=('Arial', 24, 'bold'), fg='darkblue')
count_label.pack(pady=20)

btn_inc = [Link](root, text='+1 Increment',


command=increment,
bg='green', fg='white',
font=('Arial', 12), width=14)
btn_inc.pack(pady=5)

btn_reset = [Link](root, text='Reset',


command=reset,
bg='red', fg='white',
font=('Arial', 12), width=14)
btn_reset.pack(pady=5)
[Link]()
When the '+1 Increment' button is clicked, the increment() function is called, which increases the
counter and updates the label. When 'Reset' is clicked, reset() is called to set the counter back to 0.

5.4 Entry Fields and User Input

5.4.1 Entry Widget — Single-Line Input


An Entry widget provides a single-line text input box where users can type text. It is the primary
widget for collecting text input such as names, email addresses, passwords, and numbers.
Entry Syntax
entry = [Link](parent, option=value, ...)

Option Description Example


width Width in characters 30
font Font for input text ('Arial', 12)
fg Text color 'black'
bg Background color 'white'
show Replace characters (for '*' or '•'
passwords)
state Enable/disable input 'normal','disabled','readonly'
relief Border style 'sunken','flat'
justify Text alignment 'left','center','right'
textvariable Link to a StringVar for auto- my_string_var
update

Key Entry methods:


• [Link]() — Returns the current text in the entry widget.
• [Link](0, [Link]) — Clears the entry widget.
• [Link](0, 'text') — Inserts text at specified position.
• [Link]() — Sets keyboard focus to this widget.
Program 4: Simple name input form
import tkinter as tk
from tkinter import messagebox

def greet():
name = name_entry.get()
if [Link]():
[Link]('Greeting', f'Hello, {name}! Welcome!')
else:
[Link]('Warning', 'Please enter your name!')

root = [Link]()
[Link]('Greeting App')
[Link]('320x180')
[Link](bg='#f0f0f0')

[Link](root, text='Enter your name:',


font=('Arial', 12), bg='#f0f0f0').pack(pady=10)

name_entry = [Link](root, width=25, font=('Arial', 12))


name_entry.pack(pady=5)
name_entry.focus() # Auto-focus the entry field

[Link](root, text='Greet Me!', command=greet,


bg='blue', fg='white', font=('Arial', 11)).pack(pady=10)

[Link]()

5.4.2 StringVar, IntVar, DoubleVar, BooleanVar — Tkinter Variables


tkinter provides special variable classes (StringVar, IntVar, DoubleVar, BooleanVar) that can be
linked to widgets. When the variable changes, the linked widget updates automatically, and vice
versa. These are called trace variables or control variables.
Using StringVar with Entry
import tkinter as tk

root = [Link]()
[Link]('Variable Demo')
[Link]('350x200')

name_var = [Link]() # Create StringVar

# Link StringVar to Entry


entry = [Link](root, textvariable=name_var, width=25)
[Link](pady=10)

# Label that automatically shows current entry value


display = [Link](root, textvariable=name_var,
font=('Arial', 14), fg='blue')
[Link](pady=10)

# Reading the value


def show():
print('Current value:', name_var.get())
name_var.set('Changed!') # Setting the value

[Link](root, text='Show', command=show).pack()


[Link]()

5.4.3 Text Widget — Multi-Line Input


The Text widget provides a multi-line text area for both input and output. It supports complex text
editing features including scrolling, tags for styled text, and embedded images.
Program 5: Text editor with word count
import tkinter as tk
def count_words():
content = text_area.get('1.0', [Link]).strip()
words = len([Link]()) if content else 0
chars = len(content)
[Link](text=f'Words: {words} | Characters: {chars}')

root = [Link]()
[Link]('Simple Text Editor')
[Link]('500x400')

[Link](root, text='Type your text below:',


font=('Arial', 11)).pack(anchor='w', padx=10)

text_area = [Link](root, width=60, height=18,


font=('Courier New', 11), wrap='word')
text_area.pack(padx=10, pady=5)

[Link](root, text='Count Words',


command=count_words, bg='green', fg='white').pack(pady=5)

status = [Link](root, text='Words: 0 | Characters: 0',


font=('Arial', 10), fg='gray')
[Link]()

[Link]()

5.5 Dialogs
Dialogs are pop-up windows that appear on top of the main window to convey information, ask
questions, display warnings, or collect input from the user. tkinter provides a rich collection of built-in
dialogs through the [Link], [Link], [Link], and
[Link] sub-modules.

5.5.1 messagebox — Standard Dialog Boxes


The messagebox module provides ready-made dialog boxes for common situations:
Function Type Returns Use Case
showinfo(title, msg) Information None Display informational
messages
showwarning(title, Warning None Display warnings
msg)
showerror(title, msg) Error None Display error
messages
askquestion(title, msg) Yes/No question 'yes' or 'no' Ask a yes/no question
askyesno(title, msg) Yes/No question True or False Confirm an action
askyesnocancel(title, Yes/No/Cancel True, False, or None Three-way choice
msg)
askokcancel(title, msg) OK/Cancel True or False Confirm or cancel
Function Type Returns Use Case
askretrycancel(title, Retry/Cancel True or False Retry after failure
msg)

Program 6: messagebox demonstration


import tkinter as tk
from tkinter import messagebox

def show_info():
[Link]('Information', 'File saved successfully!')

def ask_confirm():
result = [Link]('Confirm', 'Do you want to delete this
file?')
if result:
[Link]('Deleted', 'File deleted successfully!')
else:
[Link]('Cancelled', 'Deletion cancelled.')

def show_error():
[Link]('Error', 'An error occurred! File not found.')

root = [Link]()
[Link]('Dialog Demo')
[Link]('300x200')

[Link](root, text='Show Info', command=show_info,


width=15).pack(pady=5)
[Link](root, text='Ask Yes/No', command=ask_confirm,
width=15).pack(pady=5)
[Link](root, text='Show Error', command=show_error,
width=15).pack(pady=5)

[Link]()

5.5.2 filedialog — File Open/Save Dialogs


The filedialog module provides native OS file selection dialogs for opening and saving files:
Program 7: File open and save dialogs
import tkinter as tk
from tkinter import filedialog

def open_file():
filepath = [Link](
title='Select a file',
filetypes=[('Text Files', '*.txt'),
('Python Files', '*.py'),
('All Files', '*.*')]
)
if filepath:
with open(filepath, 'r') as f:
content = [Link]()
text_area.delete('1.0', [Link])
text_area.insert('1.0', content)
[Link](f'Text Viewer — {filepath}')

def save_file():
filepath = [Link](
defaultextension='.txt',
filetypes=[('Text Files', '*.txt'), ('All Files', '*.*')]
)
if filepath:
with open(filepath, 'w') as f:
[Link](text_area.get('1.0', [Link]))

root = [Link]()
[Link]('File Viewer')
[Link]('600x450')

frame = [Link](root)
[Link](fill='x', padx=5, pady=5)
[Link](frame, text='Open File', command=open_file, bg='green',
fg='white').pack(side='left', padx=2)
[Link](frame, text='Save File', command=save_file, bg='blue',
fg='white').pack(side='left', padx=2)

text_area = [Link](root, font=('Courier New', 11))


text_area.pack(fill='both', expand=True, padx=5, pady=5)

[Link]()

5.5.3 simpledialog — Simple Input Dialogs


from tkinter import simpledialog

# Ask for a string


name = [Link]('Input', 'Enter your name:')

# Ask for an integer


age = [Link]('Input', 'Enter your age:',
minvalue=1, maxvalue=120)

# Ask for a float


price = [Link]('Input', 'Enter price:',
minvalue=0.01)

5.6 Widget Attributes — Sizes, Fonts, Colors

5.6.1 Fonts
Fonts in tkinter are specified as a tuple: (family, size, style). Multiple styles can be combined.
Font specification examples
# Font as tuple: (family, size, style...)
font1 = ('Arial', 12) # Normal
font2 = ('Arial', 14, 'bold') # Bold
font3 = ('Times New Roman', 16, 'italic') # Italic
font4 = ('Courier New', 11, 'bold', 'underline') # Bold+Underline

# Using [Link] module for more control


import [Link] as tkfont

custom_font = [Link](family='Helvetica', size=13,


weight='bold', slant='roman',
underline=True)
label = [Link](root, text='Custom Font', font=custom_font)

5.6.2 Colors
Colors can be specified as named colors (English color names) or as hexadecimal RGB values
(#RRGGBB format):
Color Name Hex Code Color Name Hex Code
black #000000 white #FFFFFF
red #FF0000 darkred #8B0000
green #008000 darkgreen #006400
blue #0000FF darkblue #00008B
yellow #FFFF00 lightyellow #FFFFE0
cyan #00FFFF magenta #FF00FF
orange #FFA500 purple #800080
gray #808080 lightgray #D3D3D3

Color usage examples


# Named colors
label = [Link](root, text='Hello', fg='red', bg='lightyellow')

# Hex colors
button = [Link](root, text='Submit',
bg='#2196F3', fg='#FFFFFF', # Material Blue
activebackground='#1976D2')

# Configure widget color after creation


[Link](fg='#FF5722', bg='#E3F2FD')

5.6.3 Widget Sizes


Widget sizes can be specified in different units depending on the layout manager:
• Width and height in characters (for text widgets like Label, Button, Entry).
• Width and height in pixels (for Canvas, Frame, or when using place() manager).
• The geometry() method specifies window size in pixels: [Link]('400x300').
• padx and pady add padding around widgets; ipadx and ipady add padding inside.
Size specification examples
# Width/height in characters (for text-based widgets)
label = [Link](root, text='Name:', width=10, height=2)
button = [Link](root, text='OK', width=8, height=2)
entry = [Link](root, width=30)

# Window size and position


[Link]('600x400+100+50') # width x height + x_offset + y_offset
[Link](False, False) # Prevent resizing (width, height)
[Link](300, 200) # Minimum window size
[Link](800, 600) # Maximum window size

5.7 Layouts and Geometry Managers


tkinter provides three geometry managers for arranging widgets within a window or frame. A
geometry manager determines the position and size of each widget. You should not mix different
geometry managers within the same container — this causes unpredictable layout behavior.

5.7.1 pack() — Sequential Layout


pack() is the simplest geometry manager. It places widgets one after another in a specified direction.
Options control the fill, expansion, and anchor behavior.
Option Values Description
side 'top'(default),'bottom','left','right' Which side to pack against
fill 'none','x','y','both' Whether widget expands to fill
space
expand True or False Whether widget expands to fill
available space
anchor 'n','s','e','w','center','ne','nw','se','sw' Where to anchor widget when
there's extra space
padx pixels Horizontal external padding
pady pixels Vertical external padding
ipadx pixels Horizontal internal padding
ipady pixels Vertical internal padding

pack() examples
import tkinter as tk
root = [Link]()
[Link]('300x200')

# Stack vertically (default)


[Link](root, text='Top', bg='red', width=20).pack(side='top',
pady=2)
[Link](root, text='Middle', bg='green', width=20).pack(side='top',
pady=2)
[Link](root, text='Bottom', bg='blue', width=20).pack(side='bottom',
pady=2)
# Side by side
[Link](root, text='Left').pack(side='left', padx=5)
[Link](root, text='Right').pack(side='right', padx=5)

[Link]()

5.7.2 grid() — Table-Based Layout


grid() arranges widgets in a row-column grid (like an HTML table). It is the most commonly used
layout manager for forms and data entry screens because it naturally aligns labels with their
corresponding input fields.
Option Description Example
row Row number (0-indexed) row=0
column Column number (0-indexed) column=1
rowspan Number of rows to span rowspan=2
columnspan Number of columns to span columnspan=3
sticky Alignment within cell: N,S,E,W sticky='ew'
or combinations
padx External horizontal padding padx=5
pady External vertical padding pady=5
ipadx Internal horizontal padding ipadx=3
ipady Internal vertical padding ipady=3

Program 8: Student registration form using grid()


import tkinter as tk
from tkinter import messagebox

def submit():
name = name_var.get()
email = email_var.get()
age = age_var.get()
if not name or not email:
[Link]('Missing', 'Name and Email are required!')
return
[Link]('Registered',
f'Student Registered:\nName: {name}\nEmail: {email}\nAge: {age}')

root = [Link]()
[Link]('Student Registration')
[Link]('380x250')
[Link](bg='#f5f5f5')

# StringVar and IntVar


name_var = [Link]()
email_var = [Link]()
age_var = [Link]()
# Form fields using grid
fields = [('Full Name *', name_var), ('Email *', email_var)]
for i, (label_text, var) in enumerate(fields):
[Link](root, text=label_text, bg='#f5f5f5',
font=('Arial', 11)).grid(row=i, column=0, padx=15, pady=8,
sticky='w')
[Link](root, textvariable=var, width=25,
font=('Arial', 11)).grid(row=i, column=1, padx=5, pady=8)

[Link](root, text='Age', bg='#f5f5f5',


font=('Arial', 11)).grid(row=2, column=0, padx=15, pady=8,
sticky='w')
[Link](root, from_=1, to=100, textvariable=age_var,
width=5, font=('Arial', 11)).grid(row=2, column=1, sticky='w',
padx=5)

[Link](root, text='Register', command=submit,


bg='#1565C0', fg='white', font=('Arial', 12, 'bold'),
width=12).grid(row=3, column=0, columnspan=2, pady=15)

[Link]()

5.7.3 place() — Absolute Positioning


place() positions widgets at exact pixel coordinates. It gives the most precise control but is not
recommended for most applications because layouts break when window is resized.
place() example
label = [Link](root, text='Absolutely Placed')
[Link](x=50, y=80) # Exact pixel position

button = [Link](root, text='OK')


[Link](x=100, y=150, width=80, height=30)
Layout Manager Rule: NEVER mix pack() and grid() within the same container (frame or window).
You can use different managers in different frames, but within one container, use only one manager.
Mixing causes tkinter to freeze and throw an error.

5.8 Nested Frames


A Frame is a rectangular container widget that groups other widgets together. Frames are essential
for creating complex, organized layouts in tkinter. By nesting frames within frames, you can create
sophisticated GUI designs that would be impossible with a single container.
Each Frame can use its own geometry manager, allowing different sections of the window to have
different layout behaviors. For example, a toolbar at the top using pack(side='left'), a main content
area in the center using pack(fill='both', expand=True), and a status bar at the bottom using
pack(side='bottom', fill='x').

5.8.1 Basic Frame Usage


Program 9: Using frames for organized layout
import tkinter as tk

root = [Link]()
[Link]('Nested Frames Demo')
[Link]('500x350')

# ── Header Frame ───────────────────────────────────


header = [Link](root, bg='#1565C0', height=60)
[Link](fill='x')
header.pack_propagate(False) # Maintain fixed height
[Link](header, text='My Application', bg='#1565C0',
fg='white', font=('Arial', 18, 'bold')).pack(side='left', padx=20)

# ── Main Content Frame (left + right) ──────────────


main = [Link](root)
[Link](fill='both', expand=True)

# Left sidebar
sidebar = [Link](main, bg='#e8eaf6', width=140)
[Link](side='left', fill='y')
sidebar.pack_propagate(False)
[Link](sidebar, text='Navigation', bg='#e8eaf6',
font=('Arial', 11, 'bold')).pack(pady=10)
for item in ['Home', 'Students', 'Reports', 'Settings']:
[Link](sidebar, text=item, width=12,
relief='flat', bg='#e8eaf6').pack(pady=2)

# Right content area


content = [Link](main, bg='white')
[Link](side='left', fill='both', expand=True)
[Link](content, text='Welcome to the main content area',
bg='white', font=('Arial', 13)).pack(pady=30)

# ── Status Bar ──────────────────────────────────────


statusbar = [Link](root, bg='#bdbdbd', height=25)
[Link](side='bottom', fill='x')
statusbar.pack_propagate(False)
[Link](statusbar, text='Ready', bg='#bdbdbd',
font=('Arial', 9)).pack(side='left', padx=5)

[Link]()

5.8.2 LabelFrame — Labeled Frame Container


A LabelFrame is a variant of Frame that has a visible border and a title label. It is perfect for grouping
related widgets in a visually distinct section.
LabelFrame example
import tkinter as tk
root = [Link]()
[Link]('LabelFrame Demo')
[Link]('350x280')

# Personal info group


personal = [Link](root, text=' Personal Information ',
font=('Arial', 10, 'bold'), padx=10, pady=8)
[Link](fill='x', padx=10, pady=10)
[Link](personal, text='Name:').grid(row=0, column=0, sticky='w', pady=4)
[Link](personal, width=20).grid(row=0, column=1, pady=4)
[Link](personal, text='DOB:').grid(row=1, column=0, sticky='w', pady=4)
[Link](personal, width=20).grid(row=1, column=1, pady=4)

# Contact info group


contact = [Link](root, text=' Contact Details ',
font=('Arial', 10, 'bold'), padx=10, pady=8)
[Link](fill='x', padx=10)
[Link](contact, text='Phone:').grid(row=0, column=0, sticky='w', pady=4)
[Link](contact, width=20).grid(row=0, column=1, pady=4)

[Link]()

5.9 Multithreading
A thread is the smallest unit of execution within a process. Every running program is a process, and
within each process there can be one or more threads. By default, Python programs run in a single
thread (the main thread). Multithreading allows a program to perform multiple operations concurrently
within the same process, sharing the same memory space.
Multithreading is especially important for:
• GUI applications: Long operations (file loading, network requests, complex calculations) would
freeze the GUI if run in the main thread. Running them in a background thread keeps the GUI
responsive.
• Server applications: Each client connection can be handled in its own thread.
• I/O-bound tasks: File reading/writing, network communication, database queries.

5.9.1 The threading Module


Python's threading module provides the Thread class and synchronisation primitives (locks, events,
semaphores). The most important class is Thread.
Creating a thread
import threading

# Method 1: Pass a function to Thread


def my_task(name, n):
for i in range(n):
print(f'Thread {name}: step {i+1}')

t1 = [Link](target=my_task, args=('Alpha', 3))


t2 = [Link](target=my_task, args=('Beta', 3))

[Link]() # Start thread 1


[Link]() # Start thread 2

[Link]() # Wait for thread 1 to finish


[Link]() # Wait for thread 2 to finish
print('Both threads done')

Method 2: Subclassing Thread


import threading
import time

class WorkerThread([Link]):
def __init__(self, name, duration):
super().__init__()
[Link] = name
[Link] = duration

def run(self): # run() is called by start()


print(f'{[Link]} starting...')
[Link]([Link])
print(f'{[Link]} done after {[Link]}s')

t1 = WorkerThread('Task-1', 2)
t2 = WorkerThread('Task-2', 1)
[Link]()
[Link]()
[Link]()
[Link]()
print('All tasks complete')

5.9.2 Thread Synchronisation — Locks


When multiple threads access shared data simultaneously, they can interfere with each other,
causing inconsistent results (race conditions). A Lock (mutex) ensures that only one thread can
access a critical section of code at a time.
Program 10: Thread-safe counter using Lock
import threading

counter = 0
lock = [Link]()

def increment(n):
global counter
for _ in range(n):
with lock: # Acquire lock — only one thread at a time
counter += 1 # Critical section
# Lock auto-released when 'with' block exits

threads = [[Link](target=increment, args=(1000,))


for _ in range(5)]

for t in threads: [Link]()


for t in threads: [Link]()

print(f'Final counter: {counter}') # Should be 5000

5.9.3 Key Thread Concepts


Concept Description Usage
Thread Lightweight unit of execution [Link](target=fn,
Concept Description Usage
args=(...))
start() Begin thread execution [Link]() — calls run() in new
thread
join() Wait for thread to finish [Link]() — main thread waits
run() Override in subclass — code def run(self): ...
executed by thread
is_alive() Check if thread is still running if t.is_alive(): ...
daemon Background thread — dies with [Link] = True
main thread
Lock Mutual exclusion — prevents lock = [Link]()
race conditions
Event Signal between threads e = [Link](); [Link]();
[Link]()
Semaphore Limit concurrent access count s = [Link](3)
Timer Run function after delay [Link](5.0, fn).start()

GIL — Global Interpreter Lock: Python's CPython interpreter uses a Global Interpreter Lock (GIL)
that allows only one thread to execute Python bytecode at a time. This means Python threads cannot
truly run CPU-bound code in parallel. However, they work well for I/O-bound tasks (file, network,
database operations) because the GIL is released during I/O waits.

5.10 Networks and Client/Server Programming


Network programming enables Python programs to communicate with other computers over a local
network or the internet. At the foundation of all network communication is the socket — an endpoint
for two-way communication between processes on the same or different machines.
Python's socket module provides a low-level interface for creating network connections. Higher-level
modules ([Link], urllib, requests) are built on top of sockets and make common tasks like HTTP
requests much simpler.

5.10.1 The Client-Server Architecture


Most network applications follow the client-server model:
• Server: A program that runs continuously, listening on a specific port for incoming connections
from clients. When a client connects, the server processes the request and sends back a
response.
• Client: A program that initiates a connection to a server, sends a request, receives a
response, and then processes it.
The server must start before clients can connect. The server runs in a loop, accepting connections
one after another. For handling multiple simultaneous clients, a new thread is typically created for
each client connection.

5.10.2 Socket Programming — TCP/IP


TCP (Transmission Control Protocol) provides reliable, ordered, error-checked delivery of data
between applications. It is used for HTTP, FTP, SMTP, and most other protocols where data integrity
matters.
TCP Server Program
import socket
import threading

def handle_client(client_socket, address):


'''Handle one client connection in its own thread'''
print(f'Connected: {address}')
try:
while True:
data = client_socket.recv(1024) # Receive up to 1024 bytes
if not data:
break
message = [Link]('utf-8')
print(f'From {address}: {message}')
response = f'Echo: {message}'
client_socket.send([Link]('utf-8'))
finally:
client_socket.close()
print(f'Disconnected: {address}')

# Create TCP socket


server = [Link](socket.AF_INET, # IPv4
socket.SOCK_STREAM) # TCP

[Link](('localhost', 9999)) # Bind to address and port


[Link](5) # Listen (max 5 queued connections)
print('Server listening on port 9999...')

while True:
client_sock, addr = [Link]() # Wait for connection
# Handle each client in separate thread
t = [Link](target=handle_client, args=(client_sock, addr))
[Link] = True
[Link]()

TCP Client Program


import socket

client = [Link](socket.AF_INET, socket.SOCK_STREAM)


[Link](('localhost', 9999)) # Connect to server

messages = ['Hello Server!', 'How are you?', 'Goodbye!']


for msg in messages:
[Link]([Link]('utf-8'))
response = [Link](1024).decode('utf-8')
print(f'Server replied: {response}')

[Link]()
5.10.3 Socket Functions Reference
Function/Method Description
[Link](AF_INET, SOCK_STREAM) Create TCP/IP socket
[Link](AF_INET, SOCK_DGRAM) Create UDP/IP socket
[Link]((host, port)) Bind socket to address and port (server)
[Link](backlog) Start listening for connections (server)
[Link]() Accept incoming connection; returns (conn, addr)
(server)
[Link]((host, port)) Connect to server (client)
[Link](data) Send bytes data
[Link](bufsize) Receive up to bufsize bytes
[Link]() Close the socket
[Link](...) Set socket options (e.g., reuse address)
[Link](seconds) Set timeout for socket operations
[Link]() Get the hostname of the current machine
[Link](host) Resolve hostname to IP address

5.11 Introduction to HTML and Web Interaction


HTML (HyperText Markup Language) is the standard language for creating web pages. It uses tags
to define the structure and content of a web page. Understanding HTML is essential for web scraping,
CGI programming, and building web-based Python applications.

5.11.1 Introduction to HTML


HTML documents consist of elements defined by tags enclosed in angle brackets. Most tags come in
pairs: an opening tag and a closing tag. The browser interprets these tags to render the web page
visually.
Basic HTML structure
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
</head>
<body>
<h1>Welcome to Python Web Programming</h1>
<p>This is a paragraph of text.</p>
<a href='[Link] [Link]</a>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</body>
</html>
HTML Tag Purpose Example
<html> Root element of HTML page <html> ... </html>
<head> Contains metadata (title, <head><title>Page</title></head>
scripts, styles)
<body> Contains visible page <body> ... </body>
content
<h1>–<h6> Headings (h1 largest, h6 <h1>Main Title</h1>
smallest)
<p> Paragraph <p>Some text here.</p>
<a href='url'> Hyperlink <a href='[Link]'>Click here</a>
<img src='url'> Image <img src='[Link]' alt='Photo'>
<form> HTML form for user input <form method='POST' action='[Link]'>
<input> Input field, checkbox, radio, <input type='text' name='name'>
submit
<select> Dropdown menu <select name='city'>...</select>
<table> Table structure <table><tr><td>Data</td></tr></table>
<div> Block-level container <div class='container'>...</div>

5.11.2 Interacting with Remote HTML Servers


Python provides several libraries for communicating with web servers and downloading web content.
The most commonly used are urllib (built-in) and requests (third-party, very popular).
Using urllib to download a web page
import [Link]
import [Link]

# Simple GET request — download a web page


url = '[Link]
response = [Link](url)
html_content = [Link]().decode('utf-8')
print('Status code:', [Link]())
print('First 500 chars:')
print(html_content[:500])

Downloading a web page with requests module


import requests

# GET request
response = [Link]('[Link]
print('Status:', response.status_code)
print('Content-Type:', [Link]['Content-Type'])
print('Response (JSON):', [Link]())

# POST request (sending form data)


data = {'username': 'alice', 'password': 'secret'}
response = [Link]('[Link] data=data)
print([Link]())

5.11.3 Running HTML-Based Queries


Query strings are parameters appended to a URL after a '?' character. They are used to pass data to
web servers in GET requests. Multiple parameters are separated by '&'.
Building and sending URL queries
import [Link]
import [Link]

# Building a query string


base_url = '[Link]
params = {
'q': 'Python programming',
'lang': 'en',
'limit': '10'
}

query_string = [Link](params)
full_url = f'{base_url}?{query_string}'
print('URL:', full_url)
# [Link]

# Send the request


try:
response = [Link](full_url)
data = [Link]().decode('utf-8')
print(data[:200])
except [Link] as e:
print(f'URL Error: {e}')

5.11.4 Downloading Web Pages


Download and save a webpage to file
import [Link]
import os

def download_page(url, filename):


'''Download a web page and save it to a file'''
try:
# Add headers to mimic a browser
headers = {'User-Agent': 'Mozilla/5.0 (compatible; Python/3.x)'}
req = [Link](url, headers=headers)
response = [Link](req)
content = [Link]()
with open(filename, 'wb') as f:
[Link](content)
print(f'Saved {len(content)} bytes to {filename}')
return True
except Exception as e:
print(f'Error downloading {url}: {e}')
return False
download_page('[Link] 'python_home.html')

5.12 CGI Programming


CGI (Common Gateway Interface) is a standard protocol that enables web servers to execute
programs (scripts) in response to HTTP requests and return their output as web pages. CGI is one of
the oldest web programming technologies and forms the conceptual foundation for understanding
how web servers process requests and generate dynamic content.
In CGI programming, when a user submits an HTML form or requests a CGI URL:
7. The web browser sends an HTTP request to the server.
8. The web server identifies the request as a CGI script (usually by the .py or .cgi extension, or
by the /cgi-bin/ directory).
9. The server executes the CGI script as a subprocess.
10. The script generates HTML output (to standard output).
11. The server captures this output and sends it back to the browser as an HTTP response.

5.12.1 The cgi Module


Python's built-in cgi module provides utilities for working with CGI scripts. The key class is
[Link], which parses form data sent from the browser.
Basic CGI script structure
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cgi
import cgitb

[Link]() # Enable CGI error reporting (very useful for debugging)

# IMPORTANT: Always print the Content-Type header FIRST


print('Content-Type: text/html; charset=utf-8')
print() # Empty line separates headers from body

# Now print HTML body


print('<html><head><title>CGI Response</title></head>')
print('<body>')
print('<h1>Hello from Python CGI!</h1>')
print(f'<p>CGI script executed successfully.</p>')
print('</body></html>')

5.12.2 Programming a Simple CGI Form


A CGI form consists of two components: an HTML page with a form, and a CGI script that processes
the form data.
Step 1: HTML form ([Link])
<!DOCTYPE html>
<html>
<head><title>Student Registration</title></head>
<body>
<h2>Student Registration Form</h2>
<form method='POST' action='/cgi-bin/[Link]'>
<label>Name:</label><br>
<input type='text' name='name' size='30'><br><br>

<label>Email:</label><br>
<input type='email' name='email' size='30'><br><br>

<label>Age:</label><br>
<input type='number' name='age' min='1' max='100'><br><br>

<label>Course:</label><br>
<select name='course'>
<option value='btech'>[Link]</option>
<option value='mtech'>[Link]</option>
<option value='mca'>MCA</option>
</select><br><br>

<input type='submit' value='Register'>


<input type='reset' value='Clear'>
</form>
</body>
</html>

Step 2: CGI processing script ([Link] in cgi-bin)


#!/usr/bin/env python3

import cgi
import cgitb
import html

[Link]()

# Content-Type header
print('Content-Type: text/html; charset=utf-8')
print()

# Parse form data


form = [Link]()

# Read form fields (escape to prevent XSS)


name = [Link]([Link]('name', 'N/A'))
email = [Link]([Link]('email', 'N/A'))
age = [Link]([Link]('age', 'N/A'))
course = [Link]([Link]('course', 'N/A'))

# Generate HTML response


print(f'''<!DOCTYPE html>
<html>
<head><title>Registration Confirmation</title></head>
<body>
<h2>Registration Successful!</h2>
<table border="1" cellpadding="8">
<tr><th>Field</th><th>Value</th></tr>
<tr><td>Name</td><td>{name}</td></tr>
<tr><td>Email</td><td>{email}</td></tr>
<tr><td>Age</td><td>{age}</td></tr>
<tr><td>Course</td><td>{course}</td></tr>
</table>
<br>
<a href="/[Link]">Register Another Student</a>
</body>
</html>
''')

5.12.3 Setting Up CGI with Python's Built-in Server


Run Python's CGI-capable HTTP server
# Navigate to your project directory first
# python3 -m [Link] --cgi 8080

# Or programmatically:
import [Link]
import os

[Link]('/path/to/your/project') # Directory with cgi-bin folder

handler = [Link]
server = [Link](('localhost', 8080), handler)
print('CGI server started at [Link]
server.serve_forever()
CGI Directory Structure: For CGI to work with Python's built-in HTTP server: Create a 'cgi-bin'
directory in your project. Place Python CGI scripts (.py files) in the 'cgi-bin' directory. Access them at
[Link] The script must start with the Content-Type header.

5.12.4 CGI Environment Variables


CGI scripts receive information about the HTTP request through environment variables set by the
web server:
Variable Description Example Value
REQUEST_METHOD HTTP method used GET or POST
QUERY_STRING URL query string (for GET) name=Alice&age=20
CONTENT_TYPE Type of POST data application/x-www-form-
urlencoded
CONTENT_LENGTH Length of POST data in bytes 35
HTTP_USER_AGENT Browser/client identification Mozilla/5.0...
REMOTE_ADDR IP address of the client [Link]
SERVER_NAME Hostname of the web server localhost
SERVER_PORT Port the server is listening on 8080
SCRIPT_NAME Path to the CGI script /cgi-bin/[Link]
Reading CGI environment variables
#!/usr/bin/env python3
import os

print('Content-Type: text/html')
print()
print('<h2>CGI Environment Variables</h2>')
print('<table border="1">')
print('<tr><th>Variable</th><th>Value</th></tr>')

cgi_vars = ['REQUEST_METHOD', 'QUERY_STRING',


'HTTP_USER_AGENT', 'REMOTE_ADDR',
'SERVER_NAME', 'SERVER_PORT']

for var in cgi_vars:


val = [Link](var, 'Not Set')
print(f'<tr><td>{var}</td><td>{val}</td></tr>')

print('</table>')

5.13 Turtle Graphics (Drawing with Turtle)


The Turtle module is Python's built-in graphics package for learning programming through visual
output. It provides an easy way to draw lines, shapes, patterns, and animations on a graphics
window. The 'turtle' is a cursor (represented as an arrowhead) on the screen that can be commanded
to move, turn, and draw.
Turtle graphics was originally part of the Logo programming language, developed in the 1960s as a
tool for teaching programming to children. Python's implementation makes it accessible to beginners
while still being powerful enough for complex geometric patterns and artistic creations.

5.13.1 Getting Started with Turtle


Basic turtle setup
import turtle # Standard import

# OR: from turtle import * # Import all functions directly


# OR: import turtle as t # Use alias

[Link]() # Show the turtle cursor


# At this point, a graphics window opens
# The turtle starts at center (0,0) facing right (east)
The turtle graphics window uses a Cartesian coordinate system with the origin (0,0) at the center.
Positive x is to the right, positive y is upward. The turtle starts facing east (0 degrees) and turns anti -
clockwise by default.

5.13.2 Turtle Movement Methods


Method Description Example
forward(n) or fd(n) Move forward n pixels in current [Link](100)
Method Description Example
direction
backward(n) or bk(n) Move backward n pixels [Link](50)
left(angle) or lt(angle) Rotate left by angle degrees [Link](90)
right(angle) or rt(angle) Rotate right by angle degrees [Link](45)
goto(x, y) or setpos(x, y) Move to absolute coordinates [Link](0, -50)
setx(x) Set x-coordinate [Link](100)
sety(y) Set y-coordinate [Link](-50)
home() Return to origin (0,0) facing [Link]()
east
penup() or pu() Lift pen — move without [Link]()
drawing
pendown() or pd() Lower pen — draw when [Link]()
moving
pensize(width) Set pen line thickness [Link](3)
speed(n) Set drawing speed 0(instant)– [Link](5)
10(fastest)

5.13.3 Drawing Shapes with Turtle


Program 11: Draw a square
import turtle

[Link](100)
[Link](90)
[Link](100)
[Link](90)
[Link](100)
[Link](90)
[Link](100)
# A square is complete: moved 100px forward, turned 90° left four times

Program 12: Draw a polygon using loop


import turtle

def draw_polygon(n, side):


'''Draw regular polygon with n sides of given length'''
angle = 360 / n
for _ in range(n):
[Link](side)
[Link](angle)

draw_polygon(3, 100) # Triangle


draw_polygon(5, 80) # Pentagon
draw_polygon(6, 60) # Hexagon
Program 13: Draw circles with different radii
import turtle

for r in [45, 55, 65, 75, 85]:


[Link](r)
# Draws 5 concentric-like circles of increasing size

5.13.4 Colors and Filling


Program 14: Colored filled square
import turtle

[Link]('gray') # Set fill color


turtle.begin_fill() # Start filling
for _ in range(4):
[Link](100)
[Link](90)
turtle.end_fill() # Stop filling — applies the color

Program 15: Colored circle with text


import turtle

[Link]()
[Link]('gray')
turtle.begin_fill()
[Link](70)
turtle.end_fill()
[Link]()
[Link](-25, 50)
[Link]()
[Link]('Circle!', font=('Times New Roman', 20, 'bold'))

5.13.5 Color Methods Reference


Method Description Example
color(c) Set both pen and fill color [Link]('red')
pencolor(c) Set pen (outline) color [Link]('#FF0000')
fillcolor(c) Set fill color [Link]('blue')
begin_fill() Mark start of region to fill turtle.begin_fill()
end_fill() Fill the region turtle.end_fill()
bgcolor(c) Set background color of window [Link]('pink')
clear() Clear window, keep [Link]()
state/position
reset() Clear window, reset [Link]()
state/position
showTurtle() Make turtle visible [Link]()
hideTurtle() Make turtle invisible [Link]()
Method Description Example
screensize(w, h) Set canvas size [Link](800,600)
write(text, font=...) Write text at current position [Link]('Hi!',
font=('Arial',14,'bold'))

5.13.6 Drawing with Iterations — Creating Complex Patterns


Program 16: Draw four squares using function
import turtle

def square(side):
for i in range(4):
[Link](side)
[Link](90)

square(20)
square(30)
square(40)
square(50)

Program 17: Color-changing circles using list


import turtle as t

colors = ['blue', 'RED', 'Pink', 'green', 'orange']


for i in range(len(colors)):
[Link](colors[i])
t.begin_fill()
[Link](70)
t.end_fill()
A list of color names is defined. The for loop iterates through the list, setting a new fill color for each
iteration and drawing a circle of radius 70 in that color.
Program 18: Drawing a flower
import turtle as t

def petal(t, r, angle):


for i in range(2):
[Link](r, angle)
[Link](180 - angle)

def flower(t, n, r, angle):


for i in range(n):
petal(t, r, angle)
[Link](360.0 / n)

flower(t, 7, 80.0, 60.0)

5.13.7 Bar Charts with Turtle


Program 19: Browser usage bar chart
import turtle
def Draw_Bar_Chart(t, height):
t.begin_fill()
[Link](90)
[Link](height)
[Link](str(height))
[Link](90)
[Link](40)
[Link](90)
[Link](height)
[Link](90)
t.end_fill()

# Sample data: browser usage percentages


Mozilla_Firefox = 45
Chrome = 30
IE = 15
Others = 10

S = [Mozilla_Firefox, Chrome, IE, Others]

w = [Link]()
[Link](0, 0, 40 * len(S) + 10, max(S) + 10)
[Link]('pink')

T1 = [Link]()
[Link]('#000000')
[Link]('#DB148E')
[Link](3)

for a in S:
Draw_Bar_Chart(T1, a)

5.14 Comprehensive Worked Programs

Program 1: Complete Calculator GUI


Code
import tkinter as tk
from tkinter import messagebox

def calculate():
try:
n1 = float(num1_entry.get())
n2 = float(num2_entry.get())
op = [Link]()
if op == '+': result = n1 + n2
elif op == '-': result = n1 - n2
elif op == '*': result = n1 * n2
elif op == '/':
if n2 == 0: raise ZeroDivisionError
result = n1 / n2
result_label.config(text=f'Result: {result:.4g}')
except ValueError:
[Link]('Error', 'Please enter valid numbers!')
except ZeroDivisionError:
[Link]('Error', 'Cannot divide by zero!')

root = [Link]()
[Link]('Calculator')
[Link]('320x260')
[Link](bg='#eceff1')

[Link](root, text='Calculator', font=('Arial',16,'bold'),


bg='#1565C0', fg='white').pack(fill='x', pady=0)

form = [Link](root, bg='#eceff1', pady=10)


[Link]()

[Link](form, text='Number 1:',


bg='#eceff1').grid(row=0,column=0,padx=5,pady=5,sticky='w')
num1_entry = [Link](form, width=15);
num1_entry.grid(row=0,column=1,pady=5)

[Link](form, text='Number 2:',


bg='#eceff1').grid(row=1,column=0,padx=5,pady=5,sticky='w')
num2_entry = [Link](form, width=15);
num2_entry.grid(row=1,column=1,pady=5)

[Link](form, text='Operation:',
bg='#eceff1').grid(row=2,column=0,padx=5,sticky='w')
operation = [Link](value='+')
ops = [Link](form, bg='#eceff1')
[Link](row=2,column=1,sticky='w')
for op in ['+','-','*','/']:

[Link](ops,text=op,variable=operation,value=op,bg='#eceff1').pack(si
de='left')

[Link](root, text='Calculate', command=calculate,


bg='#1565C0', fg='white', font=('Arial',11,'bold'),
width=15).pack(pady=8)

result_label = [Link](root, text='Result: --', font=('Arial',14,'bold'),


bg='#eceff1', fg='#1565C0')
result_label.pack()
[Link]()

Program 2: Turtle Racing Game (Mini Project)


Code
from turtle import *
from random import *

title('Turtle F1 Racing Game')


speed(10)
penup()
goto(-240, 240)
# Draw the racing track
y = 25
for x in range(6):
write(x)
right(90)
forward(10)
pendown()
forward(150)
penup()
backward(160)
left(90)
forward(y)

# Create three turtles


t1 = Turtle(); [Link](); [Link](-260, 200)
[Link]('red'); [Link]('turtle')

t2 = Turtle(); [Link](); [Link](-260, 150)


[Link]('black'); [Link]('turtle')

t3 = Turtle(); [Link](); [Link](-260, 100)


[Link]('green'); [Link]('turtle')

# Run the race


for _ in range(50):
[Link](randint(1, 5))
[Link](randint(1, 5))
[Link](randint(1, 5))

Program 3: Simple Chat Server and Client


Chat Server
import socket, threading

clients = []

def broadcast(msg, sender=None):


for c in clients:
if c != sender:
try: [Link](msg)
except: [Link](c)

def handle(client, addr):


print(f'{addr} connected')
while True:
try:
msg = [Link](1024)
if not msg: break
broadcast(msg, client)
except: break
[Link](client); [Link]()
print(f'{addr} disconnected')
server = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](('localhost', 12345))
[Link](5)
print('Chat server on port 12345')
while True:
c, a = [Link]()
[Link](c)
[Link](target=handle, args=(c,a), daemon=True).start()

5.15 Unit Summary


Topic Key Points
GUI Definition Graphical User Interface — interact via windows, buttons, menus
instead of text commands
Event-Driven Programming Program waits for events (clicks, key presses); event handlers
(callbacks) execute in response
Event Loop mainloop() keeps window open and processes events continuously
tkinter Python's built-in GUI library; Tk interface; no extra installation needed
Tk() Creates the root (main) window; must be created before any widgets
Label Displays static text or image; non-editable; key options: text, font, fg,
bg, anchor, relief
Button Clickable widget; command= specifies callback; key options: text,
command, bg, fg, state
Entry Single-line text input; get() to read value; delete(0,END) to clear;
show='*' for password
Text Multi-line text area; get('1.0', END) to read all; supports tags and
images
StringVar/IntVar Control variables linked to widgets; auto-update on change; get()/set()
messagebox Dialogs: showinfo, showwarning, showerror, askyesno, askokcancel
filedialog File open/save: askopenfilename(), asksaveasfilename()
Font specification Tuple: (family, size, style) e.g. ('Arial', 14, 'bold')
Colors Named colors ('red') or hex ('#FF0000')
pack() Sequential layout; side='top/bottom/left/right'; fill, expand, padx, pady
grid() Table layout; row=, column=, sticky=, rowspan=, columnspan=
place() Absolute pixel positioning; x=, y=; least flexible
Frame Container for grouping widgets; each frame can use its own layout
manager
LabelFrame Frame with visible border and title label
Multithreading [Link](target=fn); start() launches; join() waits; daemon
threads
Lock [Link](); with lock: — prevent race conditions on shared data
Topic Key Points
GIL Global Interpreter Lock — only one thread runs Python code at a time
Socket Endpoint for network communication; [Link](AF_INET,
SOCK_STREAM)
Server socket bind() + listen() + accept() — waits for and accepts client connections
Client socket connect() + send() + recv() — connects to server and communicates
HTML HyperText Markup Language; tags define structure;
<html><head><body> structure
urllib Built-in module for HTTP requests; urlopen(), urlencode()
requests Third-party module; [Link](url), [Link](url, data=...)
CGI Common Gateway Interface; server executes script; outputs HTML to
browser
[Link] Parses form data in CGI scripts; [Link]('fieldname')
Turtle Module Built-in graphics package; forward(), left(), right(), circle(); penup/down
Turtle Drawing Color: fillcolor(), begin_fill(), end_fill(); goto(x,y) for positioning
Bar Charts (Turtle) setworldcoordinates() sets scale; draw bars using forward/left/right/fill

5.16 Review Questions

A. Multiple Choice Questions


12. Which tkinter widget is used to create a clickable element that triggers an action? a) Label
b) Entry c) Button d) Frame [Answer: c]
13. Which geometry manager arranges widgets in a row-column grid like a table? a) pack() b)
place() c) grid() d) arrange() [Answer: c]
14. What does [Link]() do in a tkinter application? a) Closes the window b) Starts the
event loop and keeps window open c) Creates the window d) Adds widgets [Answer: b]
15. Which tkinter dialog shows an information message to the user? a)
[Link]() b) [Link]() c) [Link]() d)
[Link]() [Answer: b]
16. Which turtle method draws a circle of radius 45? a) [Link](45) b) [Link](45) c)
[Link](45) d) [Link](45) [Answer: b]
17. Which turtle methods must surround shape drawing to fill it with color? a) startfill()/stopfill()
b) begin_color()/end_color() c) begin_fill()/end_fill() d) fill_start()/fill_end() [Answer: c]
18. Which Python module is used for creating TCP/IP socket connections? a) network b)
connection c) socket d) tcp [Answer: c]
19. In CGI programming, which module parses form data submitted by an HTML form? a) html
b) cgi c) form d) web [Answer: b]
20. Which threading method causes the main thread to wait for a specific thread to finish? a)
start() b) wait() c) pause() d) join() [Answer: d]
21. Which turtle instruction sets the pen size to 10 pixels? a) [Link](10) b)
[Link](10) c) [Link](10) d) [Link](10) [Answer: b]
B. True or False
22. Interactive mode cannot be used for turtle graphics programming in Python. (False — turtle
works in both interactive and script mode)
23. The turtle starts at the center (0,0) of the graphics window by default. (True)
24. pack() and grid() geometry managers can be freely mixed within the same container. (False —
mixing causes errors)
25. The 'with lock:' statement in threading auto-releases the lock when the block exits. (True)
26. Python's GIL allows multiple threads to run CPU-bound code in true parallel. (False — GIL
prevents this; use multiprocessing for CPU-bound parallelism)
27. [Link]() causes the turtle to draw when it moves. (False — pendown() draws; penup()
lifts pen so no drawing)
28. A tkinter Button's command parameter specifies the function to call when clicked. (True)
29. In CGI programming, the Content-Type header must be printed before any HTML output.
(True)
30. The Entry widget's get() method returns an integer directly if numbers are entered. (False —
always returns a string; convert with int() or float())
31. [Link](x, y) moves the turtle to the specified absolute coordinates. (True)

C. Short Answer Questions


32. Explain the event-driven programming paradigm. How does it differ from sequential
programming?
33. What is the role of mainloop() in a tkinter application? What happens if you omit it?
34. Explain the three geometry managers in tkinter (pack, grid, place). When is each used?
35. What are tkinter control variables (StringVar, IntVar)? How are they linked to widgets?
36. Explain the difference between penup() and pendown() in turtle graphics. Give a scenario
where each is used.
37. What is a thread? How is it different from a process? Why do we need threads in GUI
applications?
38. Explain the client-server model in network programming. What are the steps to create a
simple TCP server?
39. What is CGI programming? Explain how an HTML form interacts with a Python CGI script to
produce a dynamic response.
40. What is the purpose of begin_fill() and end_fill() in turtle graphics? Why must they be used as
a pair?
41. What is the LabelFrame widget and how does it differ from a regular Frame?

D. Programming Exercises
42. Write a tkinter program that has two Entry fields (for length and width) and a Button. When
clicked, the button should calculate and display the area of a rectangle in a Label.
43. Write a tkinter program with a 'File Open' button that opens a file dialog, reads the selected
file, and displays its contents in a Text widget.
44. Write a turtle program to draw a star pattern (5 points) using loops. Fill the star with a color of
your choice.
45. Write a tkinter program for a student marks entry form with fields for Name, Roll Number, and
marks in 5 subjects. Calculate and display the total, percentage, and grade when a 'Calculate'
button is pressed.
46. Write a Python program to demonstrate multithreading: create 3 threads that each count from
1 to 5 with a 0.5 second delay between counts. Show that threads run concurrently.
47. Write a turtle program to draw a bar chart for the following data: Maths=85, Science=72,
English=90, History=65. Label each bar with its value.
48. Write a Python CGI script that accepts a student's name and marks from an HTML form and
returns an HTML page showing the grade (A, B, C, F).
49. Write a Python TCP server that receives numbers from clients, calculates the square, and
sends back the result. Write a corresponding client to test it.
50. Create a tkinter-based contact book application with entries for Name, Phone, and Email.
Include Add, Display All, and Search buttons.
51. Write a turtle program to draw the Olympic rings (5 colored overlapping circles) at appropriate
positions.

E. Fill in the Blanks


52. The tkinter method ______ starts the event loop and keeps the GUI window open.
(mainloop())
53. The ______ widget displays text that cannot be edited by the user. (Label)
54. The ______ geometry manager arranges widgets in a row-column grid. (grid())
55. The ______ method of the Entry widget returns the current text value. (get())
56. turtle.______(90) rotates the turtle 90 degrees to the left. (left)
57. In turtle graphics, ______ must be called before drawing a filled shape, and ______ after.
(begin_fill(), end_fill())
58. The threading method ______ starts a thread's execution. (start())
59. The ______ method of a server socket waits for and accepts an incoming client connection.
(accept())
60. In CGI programming, the ______ header must be the first thing printed by the script. (Content-
Type)
61. The turtle method ______ moves the turtle to absolute coordinates without drawing (when pen
is up). (goto(x, y))

You might also like