Python Programmming Unit-4
Python Programmming Unit-4
Multithreaded Programming
Threads and Processes:
What Are Processes?
Computer programs are merely executables, binary (or otherwise), which reside on disk. They
do not take on a life of their own until loaded into memory and invoked by the operating system.
A process (sometimes called a heavyweight process) is a program in execution.
Each process has its own address space, memory, a data stack, and other auxiliary data to keep
track of execution. The operating system manages the execution of all processes on the system,
dividing the time fairly between all processes.
Processes can also fork or spawn new processes to perform other tasks, but each new process
has its own memory, data stack, etc., and cannot generally share information unless
interprocess communication (IPC) is employed.
What Are Threads?
Threads (sometimes called lightweight processes) are similar to processes except that they all
execute within the same process, thus all share the same context. They can be thought of as
"mini-processes" running in parallel within a main process or "main thread."
A thread has a beginning, an execution sequence, and a conclusion. It has an instruction pointer
that keeps track of where within its context it is currently running. It can be pre-empted
(interrupted) and temporarily put on hold (also known as sleeping) while other threads are
running—this is called yielding.
Multiple threads within a process share the same data space with the main thread and can
therefore share information or communicate with each other more easily than if they were
separate processes.
Threads are generally executed in a concurrent fashion, and it is this parallelism and data
sharing that enable the coordination of multiple tasks. Naturally, it is impossible to run truly in
a concurrent manner in a single CPU system, so threads are scheduled in such a way that they
run for a little bit, then yield to other threads. Throughout the execution of the entire process,
each thread performs its own, separate tasks, and communicates the results with other threads
as necessary.
• The GIL is a lock that protects access to Python objects, preventing multiple threads
from executing Python code simultaneously in Python.
• It ensures thread safety for Python's memory management (especially reference
counting for garbage collection).
• Because of the GIL, Python threads cannot achieve true parallel execution in CPU-
bound tasks.
When a call is made to external code, i.e., any C/C++ extension built-in function, the GIL will
be locked until it has completed (since there are no Python bytecodes to count as the interval).
Extension programmers do have the ability to unlock the GIL however, so you being the Python
developer shouldn't have to worry about your Python code locking up in those situations.
Exiting Threads:
When a thread completes execution of the function they were created for, they exit. Threads
may also quit by calling an exit function such as thread.exit(), or any of the standard ways of
exiting a Python process, i.e., sys.exit() or raising the SystemExit exception. There are a variety
of ways of managing thread termination. In most systems, when the main thread exits, all other
threads die without cleanup, but for some systems, they live on. Check your operating system
threaded programming documentation regarding their behavior in such occasions. Main
threads should always be good managers, though, and perform the task of knowing what needs
to be executed by individual threads, what data or arguments each of the spawned threads
requires, when they complete execution, and what results they provide.
Accessing Threads From Python:
Python supports multithreaded programming, depending on the operating system that it
isbrunning on. It is supported on most versions of Unix, including Solaris and Linux, and
Windows. Threads are not currently available on the Macintosh platform. Python uses POSIX-
compliant threads, or "pthreads," as they commonly known.
By default, threads are not enabled when building Python from source, but are available for
Windows platforms automatically from the installer. To tell whether threads are installed,
simply attempt to import the thread module from the interactive interpreter.
In such cases, you may have to recompile your Python interpreter to get access to threads.
def cpu_task():
count = 0
for _ in range(10_000_000):
count += 1
start_time = time.time()
end_time = time.time()
print(f"Time taken with threads: {end_time - start_time:.2f} seconds")
• Despite having two threads, the total time is nearly twice as slow because the GIL
prevents simultaneous execution on multiple cores.
Syntax:
thread.start_new_thread(function, args)
Output:
Thread-1: 1
Thread-2: 1
Thread-1: 2
Thread-1: 3
Thread-2: 2
Thread-1: 4
Thread-1: 5
Main thread exiting.
import _thread
import time
• The lock.acquire() method locks the resource to ensure only one thread modifies
counter at a time.
• lock.release() releases the lock after updating the counter to allow the next thread to
access i
• Declares counter as a global variable to ensure the function modifies the variable
defined outside its local scope.
• This loop iterates 100,000 times, performing the increment operation on each iteration.
• The underscore (_) is used as a placeholder variable when the loop index isn't required.
• Race Condition: A situation where multiple threads attempt to modify a shared resource
simultaneously, potentially leading to incorrect results.
import _thread
import time
def print_numbers(thread_name):
for i in range(5):
print(f"{thread_name}: {i}")
if i == 3:
print(f"{thread_name} is exiting early!")
_thread.exit() # Terminate thread
time.sleep(1)
# Creating a thread
try:
_thread.start_new_thread(print_numbers, ("Thread-1",))
except:
print("Error: Unable to start thread")
Note: Using except: without specifying the error type is sometimes acceptable in: Quick testing
or prototyping. Final cleanup code, where you want to catch all errors without detailed
handling.
Threading Module:
The threading module in Python is used to create and manage threads, which allow multiple
tasks to run concurrently within the same program. It is a high-level interface built on top of
the _thread module and is preferred for handling threads in Python.
Threading Module Objects
Here are the key objects in the threading module:
Object Description
Thread Represents an individual thread of execution.
Lock A synchronization primitive to manage thread access to shared
resources.
RLock A re-entrant lock that allows a thread to acquire the same lock
multiple times.
Condition Enables threads to wait for certain conditions to be true before
proceeding.
Event Allows one thread to signal an event while other threads wait for it.
Semaphore Limits the number of threads that can access a resource
concurrently.
Timer A thread that executes a function after a specified delay.
Barrier Synchronizes a fixed number of threads before they proceed.
Condition Methods:
Method Description
.acquire() Acquires the lock before waiting on the condition.
.release() Releases the lock.
.wait(timeout=None) Waits for another thread to call .notify() or .notify_all().
.notify() Wakes up one waiting thread.
.notify_all() Wakes up all waiting threads.
Event Methods:
Method Description
.set() Sets the event flag to True, allowing waiting threads to
proceed.
.clear() Resets the event flag to False.
.wait(timeout=None) Blocks the thread until .set() is called.
.is_set() Returns True if the event flag is True.
Semaphore Methods:
Method Description
.acquire() Decreases the internal counter. Blocks if zero.
.release() Increases the internal counter.
Timer Methods:
Method Description
.start() Starts the timer.
.cancel() Stops the timer before it finishes.
Barrier Methods:
Method Description
.wait() Blocks threads until all have called .wait().
.reset() Resets the barrier to its initial state.
.abort() Forces the barrier into a broken state.
There are two primary ways to create threads using the threading module:
• By Creating a Thread Using Thread Class with target= (Function-based approach)
• By Creating a Thread by Extending the Thread Class (Class-based approach)
The constructor for creating a thread using the Thread class in this module has the following
syntax:
Example:
import threading
import time
Output:
Number: 1
Number: 1
Number: 2
Number: 2
Number: 3
Number: 3
Number: 4
Number: 4
Number: 5
Number: 5
All threads completed!
Example:
import threading
import time
Output:
Thread-1 says: Count 1
Thread-2 says: Count 1
Thread-1 says: Count 2
Thread-2 says: Count 2
Thread-1 says: Count 3
Thread-2 says: Count 3
All threads completed!
1. .start() Method:
Starts the thread and calls the target function.
The thread begins executing asynchronously with the main thread.
Example:
import threading
def greet():
print("Hello from thread!")
t = threading.Thread(target=greet)
t.start()
Output:
Hello from thread!
2. .run() Method
The run() method contains the code that runs when the thread starts. It is called automatically
by .start() — you should not call .run() directly.
Example:
import threading
class MyThread(threading.Thread):
def run(self):
print("This is executed in a thread")
t = MyThread()
t.start()
Output:
This is executed in a thread
3. .join() Method
Ensures the main program waits for the thread to complete before continuing.
Example:
import threading
import time
def delay_task():
print("Starting task...")
time.sleep(3)
print("Task completed!")
t = threading.Thread(target=delay_task)
t.start()
Output:
Starting task...
Task completed!
Main thread resumed after thread completion
4. .is_alive() Method
Returns True if the thread is currently active (running or waiting).
Example:
import threading
import time
def task():
time.sleep(2)
t = threading.Thread(target=task)
t.start()
Output:
Is thread alive? True
Is thread alive? False
5. .daemon Property
A daemon thread runs in the background and terminates automatically when the main program
exits.
To create a daemon thread, set daemon=True before calling .start().
Example:
import threading
import time
def background_task():
while True:
print("Background task running...")
time.sleep(1)
t = threading.Thread(target=background_task, daemon=True)
t.start()
time.sleep(3)
print("Main thread finished. Daemon thread stops automatically.")
Output:
Background task running...
Background task running...
Background task running...
Main thread finished. Daemon thread stops automatically.
6. .ident Attribute
Provides the unique thread identifier.
Example:
import threading
def show_id():
print(f"Thread ID: {threading.current_thread().ident}")
t = threading.Thread(target=show_id)
t.start()
Output:
Thread ID: 140735595570944
Example Program:
import threading
# Creating a thread without setting a custom name (default name will be 'Thread-1')
t1 = threading.Thread(target=display_thread_name)
print(f"Default Thread Name: {t1.name}")
Output:
Default Thread Name: Thread-1
Updated Thread Name: CustomThread-1
Thread running with name: CustomThread-1
Main Thread Name: MainThread
8. threading.active_count()
Returns the number of currently active threads.
Example:
import threading
def task():
print("Thread running...")
t1 = threading.Thread(target=task)
t2 = threading.Thread(target=task)
t1.start()
t2.start()
print("Active thread count:", threading.active_count())
Output:
Thread running...
Thread running...
Active thread count: 3
9. threading.current_thread()
Returns the currently executing thread object.
Example:
import threading
def show_current_thread():
print(f"Current Thread: {threading.current_thread().name}")
t = threading.Thread(target=show_current_thread)
t.start()
Output:
Current Thread: Thread-1
10. threading.enumerate()
Returns a list of all active thread objects.
Example:
import threading
def task():
print("Thread running...")
t1 = threading.Thread(target=task)
t2 = threading.Thread(target=task)
t1.start()
t2.start()
Output:
Thread running...
Thread running...
Active threads: [<_MainThread(MainThread, started 140735595526976)>, <Thread(Thread-
1, started 140735595349760)>, <Thread(Thread-2, started 140735595351168)>]
GUI Programming:
A GUI application is similar to an artist's producing a painting. Conventionally, there is a single
canvas onto which the artist must put all the work. The way it works is like this: You start with
a clean slate, a "top-level" windowing object on which you build the rest of your components.
Tkinter is Python's default graphical user interface library. It is based on the Tk toolkit,
originally designed for the Tool Command Language (TCL). In Tkinter, this foundation is
known as the top-level window object.
In GUI programming, a top-level root windowing object contains all of the little windowing
objects that will be part of your complete GUI application. These can be text labels, buttons,
list boxes, etc. These individual little GUI components are known as widgets.
Tkinter Module:
Tkinter (short for "Tk Interface") is the standard GUI (Graphical User Interface) library for
Python. It provides tools to create interactive and visually appealing applications with
windows, buttons, labels, text boxes, and other widgets.
Importing Tkinter:
Before using Tkinter, you need to import it:
import tkinter as tk
from tkinter import * # Import all classes and functions
.mainloop() in Python :
In Python, .mainloop() is a method used in Tkinter to run the event loop for a Tkinter
application.
• It keeps the application running and waits for user interactions (e.g., clicks, key
presses).
• It processes events such as button clicks, window resizing, and other GUI updates.
• It prevents the program from exiting immediately after creating the GUI.
• The program remains open and responsive until the user closes the window.
• If you omit root.mainloop(), the window will appear briefly and then close immediately
because the script execution will end.
Explanation of Syntax
• import tkinter as tk → Imports the Tkinter module.
• root = tk.Tk() → Creates the main window.
• root.mainloop() → Starts the Tkinter event loop, keeping the window open
Method Description
title(string) Sets the title of the window.
geometry("widthxheight+x+y") Sets the size and position of the window.
resizable(width, height) Enables or disables window resizing (Boolean).
configure(option=value) Modifies window properties like background color.
iconbitmap("icon.ico") Sets a custom icon for the window (Windows only).
minsize(width, height) Sets the minimum size of the window.
maxsize(width, height) Sets the maximum size of the window.
state("zoomed" or "iconic") Maximizes or minimizes the window.
attributes("-alpha", value) Sets the transparency of the window (0 to 1).
focus_force() Forces the window to gain focus.
lift() Brings the window to the front.
lower() Sends the window to the background.
update() Forces the UI to refresh immediately.
after(ms, func) Calls a function after ms milliseconds.
destroy() Closes the window and stops execution.
quit() Terminates the Tkinter event loop.
Example-1:
import tkinter as tk
def change_title():
"""Changes the window title."""
root.title("New Window Title")
def change_size():
"""Changes the window size and position."""
root.geometry("500x400+200+100") # Width x Height + X Offset + Y Offset
def change_bg_color():
"""Changes the window background color."""
root.configure(bg="lightblue")
def set_transparency():
"""Sets window transparency."""
root.attributes("-alpha", 0.7) # 70% opaque
def bring_to_front():
"""Brings the window to the front."""
root.lift()
def send_to_back():
"""Sends the window to the background."""
root.lower()
def close_window():
"""Closes the window."""
root.destroy()
Output:
Example-2:
import tkinter as tk
def toggle_resizable():
"""Toggles the window's resizable property."""
current_width, current_height = root.resizable()
root.resizable(not current_width, not current_height)
def set_min_size():
"""Sets the minimum size of the window."""
root.minsize(300, 200) # Minimum width: 300, Minimum height: 200
def set_max_size():
"""Sets the maximum size of the window."""
root.maxsize(800, 600) # Maximum width: 800, Maximum height: 600
def force_update():
"""Updates the window UI immediately."""
root.update()
# Create the main window
root = tk.Tk()
root.title("Tkinter Window Methods Example")
root.geometry("500x400")
Output:
Label Class:
The Label class in Tkinter is used to display text or images in a GUI window. It is a non-
interactive widget, meaning users cannot edit or interact with it.
Syntax:
import tkinter as tk
label = tk.Label(master, text="Your Text", options...)
Example:
label = tk.Label(root, text="Hello, Tkinter!", font=("Helvetica", 16), fg="white", bg="blue",
wraplength=100)
2. Image Options:
Option Description Example
image Displays an image inside the image=photo
label.
bitmap Displays a predefined bitmap bitmap="error"
image (e.g., error, info).
import tkinter as tk
root = tk.Tk()
root.title("Tkinter Label Example")
root.mainloop()
Output:
# can’t get o/p for my PC as image type should be PNG
Example:
import tkinter as tk
def update_label():
"""Changes the label text dynamically."""
label.config(text="Updated Text!", fg="blue")
root.update() # Forces an immediate UI update
def show_text():
"""Displays the current label text."""
print("Label Text:", label.cget("text"))
def change_font():
"""Changes the font style of the label."""
label.config(font=("Courier", 16, "bold"))
def delayed_change():
"""Changes the label text after a delay."""
label.after(2000, lambda: label.config(text="Updated after 2 seconds"))
def change_color():
"""Changes the background and foreground color of the label."""
label.config(bg="lightgreen", fg="black")
def bind_click_event():
"""Binds a click event to the label."""
label.bind("<Button-1>", on_label_click)
def on_label_click(event):
"""Callback function when label is clicked."""
print("Label clicked at X:", event.x, "Y:", event.y)
def show_geometry():
"""Prints label's size and position."""
print("Geometry:", label.winfo_geometry())
print("Width:", label.winfo_width(), "Height:", label.winfo_height())
print("X:", label.winfo_x(), "Y:", label.winfo_y())
# Create the main window
root = tk.Tk()
root.title("Label Widget Methods Example")
root.geometry("400x300")
Output:
Button:
The Button class in Tkinter is used to create clickable buttons in a GUI application. It allows
users to interact with the program by triggering events when clicked.
Syntax
import tkinter as tk
button = tk.Button(parent, text="Click Me", command=callback_function, **options)
Parameters:
parent: The parent widget (e.g., root window or a Frame).
text: The label displayed on the button.
command: The function that will be executed when the button is clicked.
options: Additional customization such as font, size, background color, etc.
3. Functional Options:
Option Description
state Defines the button state: NORMAL (default), DISABLED
(greyed out), or ACTIVE (pressed). Example:
state=tk.DISABLED
cursor Changes the mouse pointer when hovered.
Example: cursor="hand2" (pointer hand)
repeatdelay Delay before repeating a command (in milliseconds).
Example: repeatdelay=500
repeatinterval Time interval between repeated button clicks (in
milliseconds). Example: repeatinterval=100
tate Defines the button state: NORMAL (default), DISABLED
(greyed out), or ACTIVE (pressed). Example:
state=tk.DISABLED
def on_click():
print("Button Clicked!")
root = tk.Tk()
root.title("Tkinter Button Example")
# Create a button
button = tk.Button(root, text="Click Me", command=on_click)
button.pack(pady=20)
root.mainloop()
def greet():
label.config(text="Hello, Tkinter!")
root = tk.Tk()
root.title("Styled Button")
root.mainloop()
Output:
def clicked():
label.config(text="Image Button Clicked!")
root = tk.Tk()
root.title("Button with Image")
# Load an image
image = Image.open("button_image.png") # Use any image path
image = image.resize((100, 50)) # Resize image
photo = ImageTk.PhotoImage(image)
root.mainloop()
Method Description
config(option=value) Updates button properties dynamically.
invoke() Simulates a button click (calls the associated command
function).
flash() Flashes the button (highlights it momentarily).
cget(option) Retrieves the current value of an option (e.g., text, bg,
state).
update() Forces the button to refresh immediately.
after(ms, func) Runs a function after ms milliseconds.
wait_variable(var) Pauses execution until a given Tkinter variable (var)
changes.
wait_window(window) Pauses execution until a specific window is closed.
wait_visibility(widget) Pauses execution until a widget becomes visible.
wait_window(window) Pauses execution until a specific window is closed.
wait_visibility(widget) Pauses execution until a widget becomes visible.
Example-1:
import tkinter as tk
def change_text():
"""Changes the text on the button."""
button.config(text="Text Changed!", fg="blue")
def get_text():
"""Retrieves and prints the button text."""
print("Button Text:", button.cget("text"))
def simulate_click():
"""Simulates a button click using invoke()."""
button.invoke()
def flash_button():
"""Flashes the button momentarily."""
button.flash()
def delayed_action():
"""Changes the button text after a delay."""
button.after(2000, lambda: button.config(text="Updated after 2 sec"))
# Create main window
root = tk.Tk()
root.title("Button Widget Methods Example")
root.geometry("300x300")
Output:
Example-2:
import tkinter as tk
from tkinter import Toplevel
def update_button():
"""Changes button text and forces an immediate update."""
button.config(text="Updating...")
root.update() # Force UI update
button.config(text="Updated!")
def wait_for_variable():
"""Pauses execution until the Tkinter variable changes."""
button.config(text="Waiting for variable...")
root.wait_variable(var) # Waits until var is modified
button.config(text="Variable Changed!")
def open_window():
"""Opens a new window and waits until it is closed."""
new_win = Toplevel(root)
new_win.title("Close me to continue")
tk.Label(new_win, text="Close this window to resume execution").pack(pady=20)
root.wait_window(new_win) # Waits until this window is closed
button.config(text="Window Closed!")
def check_visibility():
"""Hides the button and waits until it becomes visible again."""
button.pack_forget() # Hide button
root.update() # Force UI refresh
button.config(text="Waiting for visibility...")
button.wait_visibility(button) # Waits until the button is shown again
button.pack(pady=10) # Show button again
button.config(text="Visible Again!")
def change_var():
"""Changes the variable, which will unblock wait_variable()."""
var.set(1) # Changing the value of var
Entry:
The Entry widget in Tkinter is used to create a single-line text input field where users can enter
or edit text. It is commonly used for accepting user inputs such as names, passwords, or any
other short text entries.
Basic Syntax:
entry_widget = tk.Entry(master, option=value, ...)
Parameters:
entry_widget → The variable that stores the Entry widget.
tk.Entry → The class for creating an Entry widget.
master → The parent widget (e.g., root or a Frame).
option=value → Various optional parameters to customize the widget.
Example:
import tkinter as tk
root = tk.Tk()
root.title("Entry Widget Options Example")
root.mainloop()
Method Description
get() Returns the current text from the Entry widget.
insert(index, string) Inserts the given string at the specified index position.
delete(start, end) Deletes text between start and end. Use tk.END to remove
all text.
config(option=value) Updates the widget properties dynamically.
icursor(index) Moves the text cursor to the given index.
index(index) Returns the numerical index of a given position.
select_range(start, end) Selects text between start and end indices.
select_clear() Clears any selected text.
select_present() Returns True if text is selected, otherwise False.
xview(index) Scrolls the text horizontally to the specified index.
xview_scroll(number, what) Scrolls the text horizontally by a given amount (units or
pages).
focus() Sets focus to the entry field.
Method Description
get() Returns the current text from the Entry widget.
insert(index, string) Inserts the given string at the specified index position.
delete(start, end) Deletes text between start and end. Use tk.END to remove
all text.
config(option=value) Updates the widget properties dynamically.
Example-1:
import tkinter as tk
def get_text():
"""Retrieve and print the text from the entry field."""
text = entry.get()
print("Entered Text:", text)
def insert_text():
"""Insert a default text at the beginning."""
entry.insert(0, "Hello, ")
def delete_text():
"""Delete all text from the entry field."""
entry.delete(0, tk.END)
def select_text():
"""Selects a portion of text inside the entry field."""
entry.select_range(0, tk.END)
def clear_selection():
"""Clears the selected text."""
entry.select_clear()
Output:
Example-2:
import tkinter as tk
def change_style():
"""Changes the font, color, and background of the entry widget."""
entry.config(font=("Arial", 14, "bold"), fg="red", bg="lightyellow")
def move_cursor():
"""Moves the text cursor to the 5th character (index 4)."""
entry.icursor(4)
def get_index():
"""Gets the numerical index of the cursor position."""
pos = entry.index(tk.INSERT) # Gets the index where the cursor is currently placed
print("Cursor Position:", pos)
def scroll_to_start():
"""Scrolls the text to the beginning."""
entry.xview(0)
def scroll_right():
"""Scrolls the text to the right by 2 units."""
entry.xview_scroll(2, "units")
def set_focus():
"""Sets focus to the entry field."""
entry.focus()
def check_selection():
"""Checks if any text is selected and prints the result."""
if entry.select_present():
print("Text is selected!")
else:
print("No text selected.")
Output:
Text:
The Text widget in Tkinter is used to display and edit multi-line text. Unlike the Entry widget
(which only supports single-line input), the Text widget allows the user to enter, modify, and
retrieve multiple lines of text.
root = tk.Tk()
text_widget = tk.Text(root, options...)
text_widget.pack()
root.mainloop()
Option Description
height Number of visible lines (default: 24).
width Number of characters per line (default: 80).
bg Background color of the widget.
fg Foreground (text) color.
font Sets font type, size, and style.
padx / pady Internal padding (horizontal and vertical).
wrap Defines text wrapping (word, char, none).
yscrollcommand Connects a scrollbar.
Method Description
insert(index, text) Inserts text at the specified index.
get(start, end) Retrieves text from start to end.
delete(start, end) Deletes text between start and end.
index(index) Returns the position of the given index.
see(index) Scrolls the text widget to make index visible.
tag_add(tag, start, end) Adds a tag to a range of text (for styling).
tag_config(tag, options) Configures a tag (color, font, etc.).
tag_remove(tag, start, end) Removes a tag from the specified range.
mark_set(name, index) Creates a text mark at index.
mark_unset(name) Removes the specified mark.
focus_set() Moves the focus to the text widget.
Example:
import tkinter as tk
from tkinter import messagebox
def insert_text():
text_widget.insert("1.0", "Hello, this is a sample text.\n")
def get_text():
content = text_widget.get("1.0", tk.END)
messagebox.showinfo("Text Content", content)
def delete_text():
text_widget.delete("1.0", tk.END)
def show_index():
index = text_widget.index(tk.INSERT)
messagebox.showinfo("Current Index", f"Current cursor position: {index}")
def scroll_to_index():
text_widget.see(tk.END)
def add_tag():
text_widget.tag_add("highlight", "1.0", "1.5")
text_widget.tag_config("highlight", foreground="red", font=("Arial", 12, "bold"))
def remove_tag():
text_widget.tag_remove("highlight", "1.0", "1.5")
def set_mark():
text_widget.mark_set("my_mark", "2.0")
def unset_mark():
text_widget.mark_unset("my_mark")
def focus_text():
text_widget.focus_set()
# Create buttons
buttons = [
("Insert", insert_text),
("Get Text", get_text),
("Delete", delete_text),
("Show Index", show_index),
("Scroll to End", scroll_to_index),
("Add Tag", add_tag),
("Remove Tag", remove_tag),
("Set Mark", set_mark),
("Unset Mark", unset_mark),
("Focus", focus_text)
]
root.mainloop()
Output:
Frame:
The Frame widget in Tkinter is a container widget used to group other widgets together and
organize them within a GUI application. It acts as a parent for multiple widgets and helps in
managing layout effectively.
Syntax:
frame = tk.Frame(master, options)
Parameters:
Master: Parent widget (e.g., root window).
Options:
bg: Background color of the frame.
bd: Border width of the frame.
relief: Border style (flat, raised, sunken, ridge, solid, groove).
width: Width of the frame.
height: Height of the frame.
padx/pady: Padding inside the frame.
Example:
import tkinter as tk
from tkinter import messagebox
def change_bg():
frame.config(bg="lightblue")
def get_bg():
bg_color = frame.cget("bg")
messagebox.showinfo("Background Color", f"Current Background: {bg_color}")
def destroy_frame():
frame.destroy()
def show_children():
children = frame.winfo_children()
messagebox.showinfo("Children Count", f"Number of child widgets: {len(children)}")
def get_geometry():
geom = frame.winfo_geometry()
messagebox.showinfo("Frame Geometry", f"Current Geometry: {geom}")
def use_grid():
frame.grid(row=1, column=0, padx=10, pady=10)
def use_place():
frame.place(x=50, y=50, width=200, height=150)
def use_pack():
frame.pack(pady=20)
# Create Frame
frame = tk.Frame(root, width=200, height=150, bg="gray", relief="ridge", bd=5)
frame.pack(pady=20)
# Arrange buttons
buttons = [btn_change_bg, btn_get_bg, btn_destroy, btn_children, btn_geometry, btn_grid,
btn_place, btn_pack]
for btn in buttons:
btn.pack(pady=2, fill="x")
root.mainloop()
Output:
Canvas:
The Canvas widget in Python’s Tkinter module is used to draw shapes, images, or text on a
GUI application. It is highly flexible and allows users to create interactive graphics.
Syntax:
from tkinter import Canvas
canvas = Canvas(master, options)
Options:
Option Description
bg Background color of the canvas (e.g., "white", "blue").
bd Border width in pixels (default: 2).
cursor Mouse cursor appearance (e.g., "arrow", "circle", "hand2").
height Height of the canvas in pixels.
width Width of the canvas in pixels.
relief Border style ("flat", "raised", "sunken", "ridge", "solid",
"groove").
highlightbackground Background color of the focus highlight.
highlightcolor Color of the highlight when the widget has focus.
highlightthickness Width of the highlight border.
scrollregion Defines the scrollable area of the canvas as a tuple (x1, y1, x2,
y2).
takefocus Determines if the widget can receive focus (default: False).
xscrollcommand Associates a horizontal scrollbar.
yscrollcommand Associates a vertical scrollbar.
cursor Mouse cursor appearance (e.g., "arrow", "circle", "hand2").
Example:
from tkinter import Tk, Canvas, Button, PhotoImage
def move_rectangle():
"""Moves the rectangle 10 pixels to the right."""
canvas.move(rect, 10, 0)
def change_color():
"""Changes the rectangle's color to blue."""
canvas.itemconfig(rect, fill="blue")
def delete_text():
"""Deletes the text from the canvas."""
canvas.delete(text)
def update_coords():
"""Updates the coordinates of the oval."""
canvas.coords(oval, 300, 50, 400, 150)
def bind_event(event):
"""Changes polygon color on clicking."""
canvas.itemconfig(polygon, fill="red")
def unbind_event():
"""Removes event binding from the polygon."""
canvas.tag_unbind(polygon, "<Button-1>")
root = Tk()
root.title("Canvas Widget Demonstration")
root.geometry("600x500")
# Create a Canvas
canvas = Canvas(root, width=500, height=400, bg="white")
canvas.pack()
root.mainloop()
Example:
Checkbutton
The Checkbutton widget in Tkinter provides a toggle button that allows users to select or
deselect an option. It is often used for multiple-choice selections in GUI applications.
Syntax
from tkinter import Checkbutton
check = Checkbutton(master, options)
• master: The parent window (e.g., Tk or Frame).
• options: Various styling and functionality options.
Options:
Option Description
bg Background color of the checkbutton.
bd Border width (default: 2 pixels).
cursor Cursor style when hovering over the widget (e.g., "hand2",
"arrow").
fg Foreground (text) color.
font Font style (e.g., "Arial 12 bold").
height Height of the Checkbutton in lines.
width Width of the Checkbutton in characters.
padx Horizontal padding inside the button.
pady Vertical padding inside the button.
relief Border style ("flat", "raised", "sunken", "ridge", "solid",
"groove").
selectcolor Background color of the check when selected.
selectimage Image to show when selected instead of a check mark.
state State of the widget ("normal", "disabled", "active").
text Text displayed next to the checkbox.
underline Index of character in text to underline (for keyboard shortcuts).
variable Stores the state of the checkbox (use IntVar() or
BooleanVar()).
onvalue Value when the checkbox is checked (default: 1).
offvalue Value when the checkbox is unchecked (default: 0).
command Function to call when the state changes.
image Image to display instead of text.
indicatoron True (default) for a checkbox, False for a push button style.
Methods associated with Checkbutton Widget:
Method Description
deselect() Deselects the checkbutton.
select() Selects the checkbutton.
toggle() Toggles between selected and deselected states.
config(options) Modifies properties such as text, font, etc.
invoke() Simulates a button press and calls the associated function.
flash() Makes the button flash between active and normal states.
cget(option) Retrieves the value of an option (e.g., text, state).
Example:
from tkinter import Tk, Checkbutton, IntVar, Button, Label
def show_status():
"""Displays the current state of the Checkbutton."""
status_label.config(text=f"Checked: {var.get()}")
def toggle_check():
"""Toggles the state of the Checkbutton."""
check.toggle()
show_status()
def select_check():
"""Selects the Checkbutton."""
check.select()
show_status()
def deselect_check():
"""Deselects the Checkbutton."""
check.deselect()
show_status()
def flash_check():
"""Flashes the Checkbutton."""
check.flash()
def get_text():
"""Displays the text of the Checkbutton."""
text_label.config(text=f"Text: {check.cget('text')}")
def invoke_check():
"""Invokes the Checkbutton's command (simulates click)."""
check.invoke()
# Create a Checkbutton
check = Checkbutton(root, text="Accept Terms", variable=var, command=show_status)
check.pack(pady=10)
Output:
Radiobutton:
The Radiobutton widget in Tkinter is used to create multiple choice options where the user can
select only one option from a group. Multiple Radiobuttons are grouped using a shared variable
(IntVar() or StringVar()).
Syntax:
from tkinter import Radiobutton
radio = Radiobutton(master, options)
Options:
Option Description
activebackground Background color when the radio button is active.
activeforeground Text color when the radio button is active.
bg Background color of the widget.
bd Border width (default: 2).
cursor Mouse cursor when hovering (e.g., "hand2", "arrow").
fg Foreground (text) color.
font Font style (e.g., "Arial 12 bold").
height Height of the radio button (in lines).
width Width of the radio button (in characters).
highlightcolor Color of the highlight when the widget has focus.
highlightbackground Background color of the focus highlight.
image Image to display instead of text.
indicatoron True (default) for radio buttons, False for button-style.
justify Justifies text ("left", "right", "center").
padx Horizontal padding inside the button.
pady Vertical padding inside the button.
relief Border style ("flat", "raised", "sunken", "ridge", "solid",
"groove").
selectcolor Background color of the radio button when selected.
state State of the widget ("normal", "disabled", "active").
text Text displayed next to the radio button.
underline Index of the character in text to underline (for keyboard
shortcuts).
variable Shared variable (IntVar() or StringVar()) to group radio
buttons.
value The value assigned to the radio button when selected.
command Function to call when the radio button is selected.
Methods associated with Radiobutton:
Method Description
deselect() Deselects the radiobutton.
select() Selects the radiobutton.
invoke() Simulates a button press and triggers the associated
function.
config(option=value) Modifies properties such as text, font, color, etc.
cget(option) Retrieves the value of an option (e.g., text, state).
Example:
from tkinter import Tk, Radiobutton, IntVar, Button, Label
def show_selection():
"""Displays the selected option."""
selection_label.config(text=f"Selected: {var.get()}")
def select_option1():
"""Selects the first radiobutton."""
radio1.select()
show_selection()
def select_option2():
"""Selects the second radiobutton."""
radio2.select()
show_selection()
def invoke_option():
"""Invokes the second radiobutton."""
radio2.invoke()
show_selection()
def get_text():
"""Gets and displays the text of the selected radiobutton."""
selected_radio = radio1 if var.get() == 1 else radio2
text_label.config(text=f"Text: {selected_radio.cget('text')}")
def change_text():
"""Changes the text of the first radiobutton."""
radio1.config(text="Updated Option 1")
show_selection()
# Create Radiobuttons
radio1 = Radiobutton(root, text="Option 1", variable=var, value=1,
command=show_selection)
radio2 = Radiobutton(root, text="Option 2", variable=var, value=2,
command=show_selection)
radio1.pack(pady=5)
radio2.pack(pady=5)
Output:
Listbox:
The Listbox widget in Tkinter allows users to display a list of items and select one or multiple
items from the list.
Syntax:
from tkinter import Listbox
listbox = Listbox(master, options)
Options:
Option Description
bg Background color of the listbox.
bd Border width (default: 2).
cursor Mouse cursor when hovering (e.g., "hand2", "arrow").
exportselection True (default) to allow selection to be exported to clipboard.
fg Foreground (text) color.
font Font style (e.g., "Arial 12 bold").
height Number of visible rows (default: 10).
width Number of characters per line.
highlightcolor Color of the highlight when the widget has focus.
highlightbackground Background color of the focus highlight.
justify Aligns text ("left", "right", "center").
relief Border style ("flat", "raised", "sunken", "ridge", "solid",
"groove").
selectbackground Background color of selected item(s).
selectforeground Foreground color of selected item(s).
selectmode Selection mode:
Selection mode:
• "single": One item at a time (default).
• "browse": Similar to "single", allows moving selection with arrow keys.
• "multiple": Allows selecting multiple items.
• "extended": Allows multiple selections using Shift/Ctrl keys. | | xscrollcommand |
Connects horizontal scrollbar. | | yscrollcommand | Connects vertical scrollbar. |
Method Description
insert(index, *elements) Inserts item(s) at the specified position.
delete(start, end=None) Deletes item(s) from the listbox.
size() Returns the number of items in the listbox.
get(start, end=None) Retrieves item(s) from the listbox.
curselection() Returns the index of the currently selected item(s).
activate(index) Activates the item at the given index.
select_set(start, end=None) Selects an item (or range of items).
select_clear(start, Clears selection for the specified range.
end=None)
select_includes(index) Returns True if the given index is selected.
see(index) Scrolls the listbox to make the given index visible.
nsert(index, *elements) Inserts item(s) at the specified position.
Example:
from tkinter import Tk, Listbox, Button, END
def add_item():
"""Adds an item to the Listbox."""
listbox.insert(END, f"Item {listbox.size() + 1}")
def remove_selected():
"""Removes the selected item from the Listbox."""
selected_indices = listbox.curselection()
for index in reversed(selected_indices): # Remove from last to avoid index shift
listbox.delete(index)
def get_selected():
"""Gets and prints the selected item(s)."""
selected_indices = listbox.curselection()
selected_items = [listbox.get(i) for i in selected_indices]
print("Selected:", selected_items)
def clear_selection():
"""Clears the selection."""
listbox.select_clear(0, END)
def activate_first():
"""Activates the first item."""
listbox.activate(0)
def select_first_two():
"""Selects the first two items."""
listbox.select_set(0, 1)
def check_selection():
"""Checks if an item at index 1 is selected."""
is_selected = listbox.select_includes(1)
print(f"Item 2 selected: {is_selected}")
# Create Listbox
listbox = Listbox(root, selectmode="extended", width=25, height=10)
listbox.pack(pady=10)
Syntax:
from tkinter import Scrollbar
scrollbar = Scrollbar(master, options)
• master: The parent widget (e.g., Tk() or Frame).
• options: Various properties to customize the Scrollbar.
Option Description
bg Background color of the scrollbar.
bd Border width (default: 2).
cursor Mouse cursor when hovering (e.g., "hand2", "arrow").
elementborderwidth Border width of the scroll bar’s elements.
highlightbackground Background color when the scrollbar does not have focus.
highlightcolor Color when the scrollbar has focus.
highlightthickness Thickness of the highlight border.
jump 1 to jump to the clicked position, 0 to scroll smoothly.
orient "vertical" (default) or "horizontal".
relief Border style ("flat", "raised", "sunken", "ridge", "solid",
"groove").
repeatdelay Time in milliseconds before repeat action starts.
repeatinterval Time in milliseconds between repeat actions.
takefocus Determines if the widget should accept focus during tab
navigation.
troughcolor Color of the scrollbar's background track.
def scroll_to_bottom():
"""Moves the scrollbar to the bottom."""
text.yview_moveto(1) # Moves to the bottom of the text widget
def scroll_to_top():
"""Moves the scrollbar to the top."""
text.yview_moveto(0) # Moves to the top
def horizontal_scroll():
"""Moves the horizontal scrollbar to the right."""
canvas.xview_moveto(1)
listbox.pack(side="left", fill="y")
list_scroll.pack(side="left", fill="y")
text.pack(fill="both", expand=True)
text_scroll.pack(side=RIGHT, fill=Y)
canvas.pack(fill="both", expand=True)
h_scroll.pack(fill=X)
Output:
Spinbox:
The Spinbox widget in Tkinter is used to select from a fixed range of values by clicking the up
and down arrows.
Syntax:
from tkinter import Spinbox
spinbox = Spinbox(master, options)
Options:
Option Description
from_ Starting value (e.g., from_=1).
to Ending value (e.g., to=10).
increment Step size (e.g., increment=2 for even numbers).
values Tuple of predefined values (e.g., values=(10, 20, 30)).
wrap If True, loops from last to first value.
width Width of the widget.
justify Aligns text ("left", "right", "center").
state "normal" (default) or "disabled".
command Function to execute when the value changes.
textvariable Tkinter variable (IntVar, StringVar) for dynamic value updates.
font Font style (e.g., "Arial 12 bold").
bg Background color.
fg Foreground (text) color.
bd Border width.
cursor Mouse cursor style (e.g., "hand2", "arrow").
Example:
from tkinter import Tk, Spinbox, Button, Label, StringVar
def show_value():
"""Displays the selected value."""
label.config(text=f"Selected: {spinbox.get()}")
def set_value():
"""Sets the Spinbox to a specific value."""
spinbox.delete(0, "end") # Clears current value
spinbox.insert(0, "5") # Inserts a new value
def configure_spinbox():
"""Updates Spinbox properties dynamically."""
spinbox.configure(from_=10, to=50, increment=5)
# Create a Spinbox
spinbox = Spinbox(root, from_=1, to=10, increment=1, wrap=True, width=10)
spinbox.pack(pady=10)
Output:
Menu:
The Menu widget in Tkinter is used to create drop-down menus, context menus, and menubars
in a GUI application.
Syntax:
from tkinter import Menu
menu = Menu(master, options)
• master: The parent widget (e.g., Tk() or Frame).
• options: Various properties to customize the Menu.
options:
Option Description
bg Background color of the menu.
fg Foreground (text) color of menu items.
bd Border width of the menu.
cursor Mouse cursor appearance when hovering over the menu.
activebackground Background color when an item is hovered.
activeforeground Foreground (text) color when an item is hovered.
tearoff If 0, prevents the menu from being torn off into a separate window.
Default is 1.
postcommand A function to be called before displaying the menu.
relief Border style ("flat", "raised", "sunken", "ridge", "solid", "groove").
Example:
from tkinter import Tk, Menu, messagebox
def new_file():
"""Displays a message for 'New File'."""
messagebox.showinfo("Menu Action", "New File Created")
def open_file():
"""Displays a message for 'Open File'."""
messagebox.showinfo("Menu Action", "File Opened")
def exit_app():
"""Closes the application."""
root.quit()
def modify_menu():
"""Modifies an existing menu item."""
file_menu.entryconfig(1, label="Opened File", command=open_file)
def delete_menu_item():
"""Deletes the 'Exit' option from the menu."""
file_menu.delete(2) # Deletes the third item (Exit)
Output:
Scale:
The Scale widget in Tkinter is used to select a numerical value from a range by sliding a control
(slider).
Syntax:
from tkinter import Scale
scale = Scale(master, options)
• master: The parent widget (e.g., Tk() or Frame).
• options: Various properties to customize the Scale.
options:
Option Description
from_ Starting value (e.g., from_=0).
to Ending value (e.g., to=100).
orient Orientation ("horizontal" or "vertical").
length Length of the scale in pixels.
width Width of the scale in pixels.
sliderlength Length of the slider button.
resolution Step size (e.g., resolution=5 moves in steps of 5).
tickinterval Interval between labeled values on the scale.
showvalue If 0, hides the value label. Default is 1 (shows value).
variable Tkinter variable (IntVar, DoubleVar) for storing value.
label Displays a label above the scale.
command Function executed when scale value changes.
state "normal" (default) or "disabled".
bg Background color.
fg Foreground (text) color.
font Font style (e.g., "Arial 12 bold").
Example:
from tkinter import Tk, Scale, Label, Button
def show_value():
"""Displays the selected value."""
label.config(text=f"Selected: {scale.get()}")
def set_value():
"""Sets the Scale to a specific value."""
scale.set(50)
def configure_scale():
"""Updates Scale properties dynamically."""
scale.configure(from_=10, to=200, resolution=10)
Syntax:
from tkinter import ttk
progressbar = ttk.Progressbar(master, options)
options:
Option Description
mode "determinate" (fixed progress) or "indeterminate" (continuous
animation).
maximum Maximum progress value (default is 100).
value Current progress value.
length Length of the progress bar in pixels.
orient Orientation ("horizontal" or "vertical").
variable Tkinter variable (IntVar, DoubleVar) to store progress.
style Custom style for the progress bar.
Methods associated with Progressbar:
Method Description
start(interval) Starts the progress bar (only for "indeterminate" mode). The
interval defines speed (milliseconds).
stop() Stops the progress bar animation.
step(amount) Increments the progress by a specified amount.
config(option=value) Changes properties dynamically.
get() Returns the current progress value.
set(value) Sets the progress to a specific value.
Example:
from tkinter import Tk, Button, ttk
def start_progress():
"""Starts indeterminate progress bar animation."""
progressbar.start(10) # Moves every 10ms
def stop_progress():
"""Stops the progress bar animation."""
progressbar.stop()
def step_progress():
"""Steps progress by 10 units."""
progressbar.step(10)
def set_progress():
"""Sets progress to 50%."""
progressbar["value"] = 50
def get_progress():
"""Displays the current progress value."""
print(f"Current Progress: {progressbar['value']}")
def configure_progress():
"""Dynamically changes Progressbar properties."""
progressbar.config(maximum=200, length=300)
The Tix module is already available in the Python Standard Library. You must download the
others, which are third party. Since Pmw is just an extension to Tkinter, it is the easiest to install
(just extract it into your site packages). wxPython and PyGTK involve the download of more
than one file and building. Once the toolkits are installed and verified, we can begin.
Our application is fairly basic: pairs of animals are being moved around, and the number of
total animals can range from a pair to a maximum of a dozen. The Control is used to keep track
of the total number, while the ComboBox is a menu containing the various types of animals
that can be selected. In Figure 5-8, each image shows the state of the GUI application
immediately after launching. Note that the default number of animals is two, and no animal
type has been selected yet.
i). Tk Interface eXtensions (Tix)
Tix is an extension library for Tcl/Tk that adds many new widgets, image types, and other
commands that keep Tk a viable GUI development toolkit.
Example-1 Tix GUI Demo (animalTix.pyw)
Our first example uses the Tix module. Tix comes with Python!
1 #!/usr/bin/env python
2
3 from Tkinter import Label, Button, END
4 from Tix import Tk, Control, ComboBox
5
6 top = Tk()
7 top.tk.eval('package require Tix')
8
9 lb = Label(top,
10 text='Animals (in pairs; min: pair, max: dozen)')
11 lb.pack()
12
13 ct = Control(top, label='Number:',
14 integer=True, max=12, min=2, value=2, step=2)
15 ct.label.config(font='Helvetica -14 bold')
16 ct.pack()
17
18 cb = ComboBox(top, label='Type:', editable=True)
19 for animal in ('dog', 'cat', 'hamster', 'python'):
20 cb.insert(END, animal)
21 cb.pack()
22
23 qb = Button(top, text='QUIT',
24 command=top.quit, bg='red', fg='white')
25 qb.pack()
26
27 top.mainloop()
Our third example uses wxPython (and wxWidgets). Note that we have placed all of our
widgets inside a “sizer” for organization. Also, take note of the more object-oriented nature of
this application.
1 #!/usr/bin/env python
2
3 import wx
4
5 class MyFrame(wx.Frame):
6 def __init__(self, parent=None, id=-1, title=''):
7 wx.Frame.__init__(self, parent, id, title,
8 size=(200, 140))
9 top = wx.Panel(self)
10 sizer = wx.BoxSizer(wx.VERTICAL)
11 font = wx.Font(9, wx.SWISS, wx.NORMAL, wx.BOLD)
12 lb = wx.StaticText(top, -1,
13 'Animals (in pairs; min: pair, max: dozen)')
14 sizer.Add(lb)
15
16 c1 = wx.StaticText(top, -1, 'Number:')
17 c1.SetFont(font)
18 ct = wx.SpinCtrl(top, -1, '2', min=2, max=12)
19 sizer.Add(c1)
20 sizer.Add(ct)
21
22 c2 = wx.StaticText(top, -1, 'Type:')
23 c2.SetFont(font)
24 cb = wx.ComboBox(top, -1, '',
25 choices=('dog', 'cat', 'hamster','python'))
26 sizer.Add(c2)
27 sizer.Add(cb)
28
29 qb = wx.Button(top, -1, "QUIT")
30 qb.SetBackgroundColour('red')
31 qb.SetForegroundColour('white')
32 self.Bind(wx.EVT_BUTTON,
33 lambda e: self.Close(True), qb)
34 sizer.Add(qb)
35
36 top.SetSizer(sizer)
37 self.Layout()
38
39 class MyApp(wx.App):
40 def OnInit(self):
41 frame = MyFrame(title="wxWidgets")
42 frame.Show(True)
43 self.SetTopWindow(frame)
44 return True
45
46 def main():
47 pp = MyApp()
48 app.MainLoop()
49
50 if __name__ == '__main__':
51 main()