0% found this document useful (0 votes)
2 views

Python Programmming Unit-4

This document provides an overview of multithreaded programming, explaining the differences between processes and threads, and detailing how Python implements threading with the Global Interpreter Lock (GIL). It covers thread creation, management, synchronization, and various threading modules in Python, including examples of thread usage and the impact of the GIL on performance. Additionally, it describes methods for creating threads using both function-based and class-based approaches.

Uploaded by

venkatasai012345
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)
2 views

Python Programmming Unit-4

This document provides an overview of multithreaded programming, explaining the differences between processes and threads, and detailing how Python implements threading with the Global Interpreter Lock (GIL). It covers thread creation, management, synchronization, and various threading modules in Python, including examples of thread usage and the impact of the GIL on performance. Additionally, it describes methods for creating threads using both function-based and class-based approaches.

Uploaded by

venkatasai012345
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
You are on page 1/ 96

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.

Python Threads: the Global Interpreter Lock (GIL):


Execution by Python code is controlled by the Python Virtual Machine (a.k.a. the interpreter
main loop), and Python was designed in such a way that only one thread of control may be
executing in this main loop, similar to how multiple processes in a system share a single CPU.
Many programs may be in memory, but only one is live on the CPU at any given moment.
Likewise, although multiple threads may be "running" within the Python interpreter, only one
thread is being executed by the interpreter at any given time. Access to the Python Virtual
Machine is controlled by a global interpreter lock (GIL). This lock is what ensures that exactly
one thread is running. The Python Virtual Machine executes in the following manner in an MT
environment:

➢ Set the GIL,


➢ Switch in a thread to run,
➢ Execute for a specified number of bytecode instructions,
➢ Put the thread back to sleep (switch out thread),
➢ Unlock the GIL, and,
➢ Do it all over again (rinse, lather, repeat).

• 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.

No errors occur when threads are available:


>>> import thread
>>>
If your Python interpreter was not compiled with threads enabled, the module import fails:
>>> import thread
Traceback (innermost last):
File "<stdin>", line 1, in ?
ImportError: No module named thread

In such cases, you may have to recompile your Python interpreter to get access to threads.

Example: Showing GIL Impact on CPU-bound Tasks


Here’s an example demonstrating how the GIL limits CPU-bound performance:

Code Without Multiprocessing (Using Threads) - Limited by GIL:


import threading
import time

def cpu_task():
count = 0
for _ in range(10_000_000):
count += 1
start_time = time.time()

# Creating two threads


thread1 = threading.Thread(target=cpu_task)
thread2 = threading.Thread(target=cpu_task)

# Starting both threads


thread1.start()
thread2.start()

# Wait for both threads to finish


thread1.join()
thread2.join()

end_time = time.time()
print(f"Time taken with threads: {end_time - start_time:.2f} seconds")

Output (Limited by GIL)


Time taken with threads: 2.05 seconds

• Despite having two threads, the total time is nearly twice as slow because the GIL
prevents simultaneous execution on multiple cores.

Python Threading Modules


Python provides several modules to support multi-threaded programming, including the
thread, threading, and Queue modules. The thread and threading modules allow the
programmer to create and manage threads. The thread module provides the basic thread and
locking support, while threading provides high-level full-featured thread management. The
Queue module allows the user to create a queue data structure which can be shared across
multiple threads.
Thread Module:
The thread module (also known as _thread in Python 3) is a low-level module used for creating
and managing threads in Python. Since Python 3, the thread module has been replaced by the
more advanced threading module.
However, understanding the thread module is useful for legacy code or for learning the core
concepts behind threading.
Thread module methods:
Function Description
start_new_thread(func, args) Starts a new thread that calls the specified function.
exit() Exits the current thread.
allocate_lock() Creates a lock object for thread synchronization.

Lock Object methods:


acquire() attempts to acquire lock object
locked() returns 1 if lock acquired, 0 otherwise
release() releases lock

Creating a Thread using start_new_thread()


The primary method in the thread module is start_new_thread().

Syntax:
thread.start_new_thread(function, args)

function → The function that the thread will execute.


args → The arguments passed to the function (must be a tuple, even for a single argument).

Example 1: Simple Thread Creation


import _thread
import time

# Function to print numbers


def print_numbers(thread_name, delay):
for i in range(1, 6):
time.sleep(delay)
print(f"{thread_name}: {i}")

# Creating two threads


_thread.start_new_thread(print_numbers, ("Thread-1", 1)) # Runs every 1 second
_thread.start_new_thread(print_numbers, ("Thread-2", 2)) # Runs every 2 seconds

# Main thread runs while child threads are active


time.sleep(7) #The time.sleep() in the main thread ensures the child threads get
enough time to complete their tasks before the main thread exits.
print("Main thread exiting.")

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.

Example 2: Using allocate_lock() for Thread Synchronization


Locks are crucial in multi-threaded programs to avoid race conditions when multiple threads
access shared resources.

import _thread
import time

# Creating a lock object


lock = _thread.allocate_lock()
# Shared resource
counter = 0

# Function to increment counter


def increment_counter(thread_name):
global counter
for _ in range(100000):
lock.acquire() # Lock the shared resource
counter += 1
lock.release() # Unlock after modifying

# Creating two threads


try:
_thread.start_new_thread(increment_counter, ("Thread-1",))
_thread.start_new_thread(increment_counter, ("Thread-2",))
except:
print("Error: Unable to start thread")

# Delay to allow threads to finish


time.sleep(2)

print(f"Final Counter Value: {counter}")


Output:
Final Counter Value: 200000

• 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.

Example 3: Using exit() to Terminate a Thread


The exit() function is used to safely terminate a thread.

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")

# Delay for the thread to execute


time.sleep(6)
print("Main thread exiting.")
Output:
Thread-1: 0
Thread-1: 1
Thread-1: 2
Thread-1: 3
Thread-1 is exiting early!
Main thread exiting.

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.

Threading Module Methods


Here’s a comprehensive list of important threading module methods:
Thread Methods:
Method Description
.start() Starts the thread’s activity.
.run() Method that describes the thread’s activity (should be overridden
in custom threads).
.join(timeout=None) Blocks the main thread until the thread completes or the timeout
expires.
.is_alive() Returns True if the thread is still running.
.getName() Returns the thread’s name. (Deprecated, use .name property
instead)
.setName(name) Sets the thread’s name. (Deprecated, use .name property instead)
.ident Returns the thread’s unique identifier.
.daemon Property to set or get the daemon status.

Lock and RLock Methods:


Method Description
.acquire(timeout=None) Acquires the lock, blocks other threads if it's already locked.
.release() Releases the lock, allowing other threads to proceed.
.locked() Returns True if the lock is already acquired.

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.

Utility Methods in threading Module:


Method Description
threading.active_count() Returns the number of currently active threads.
threading.current_thread() Returns the current thread object.
threading.enumerate() Returns a list of all active thread objects.
threading.main_thread() Returns the main thread object.

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)

Creating Threads Using Thread Class with target= (Function-based approach):


This method uses the target= parameter to specify the function to be executed in the thread.

The constructor for creating a thread using the Thread class in this module has the following
syntax:

Threading.Thread(group=None, target=None, name=None, args=(), kwargs=None, *,


daemon=None)
Parameters:

• group: Should always be None. Reserved for future use.


• target: The function to be executed by the thread.
• name: Name of the thread (optional).
• args: Tuple of arguments to pass to the target function.
• kwargs: Dictionary of keyword arguments to pass to the target function.
• daemon: If True, the thread will run as a daemon thread (will not prevent the program
from exiting).

Example:
import threading
import time

# Function to be executed as a thread


def display_numbers():
for i in range(1, 6):
print(f"Number: {i}")
time.sleep(1)

# Creating thread objects


t1 = threading.Thread(target=display_numbers)
t2 = threading.Thread(target=display_numbers)

# Starting the threads


t1.start()
t2.start()

# Wait for threads to complete


t1.join()
t2.join()

print("All threads completed!")

Output:
Number: 1
Number: 1
Number: 2
Number: 2
Number: 3
Number: 3
Number: 4
Number: 4
Number: 5
Number: 5
All threads completed!

Creating Threads by Extending the Thread Class (Class-based approach)


This method involves defining a custom class that inherits from threading.Thread. The run()
method must be overridden to define the thread’s behavior.

Example:
import threading
import time

# Custom class extending Thread


class MyThread(threading.Thread):
def run(self):
for i in range(1, 4):
print(f"{self.name} says: Count {i}")
time.sleep(1)

# Creating thread objects


t1 = MyThread()
t2 = MyThread()

# Starting the threads


t1.start()
t2.start()

# Wait for threads to complete


t1.join()
t2.join()

print("All threads completed!")

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!

Exploring threading Methods with Examples

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()

# Ensure main thread waits for `t` to finish


t.join()
print("Main thread resumed after thread completion")

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()

print("Is thread alive?", t.is_alive()) # True


time.sleep(3)
print("Is thread alive?", t.is_alive()) # False

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

7. .getName() and .setName() Methods


These methods are deprecated. Use .name property instead.
The .name property in Python’s threading module is used to:

• Get the name of a thread.


• Set a custom name for a thread.

Example Program:
import threading

# Function to display thread name


def display_thread_name():
print(f"Thread running with name: {threading.current_thread().name}")

# 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}")

# Setting a custom thread name


t1.name = "CustomThread-1"
print(f"Updated Thread Name: {t1.name}")

# Starting the thread


t1.start()

# Main thread's name


print(f"Main Thread Name: {threading.current_thread().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()

print("Active threads:", threading.enumerate())

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.

Main Components of Tkinter:


1. Widgets (GUI Elements)
Tkinter provides several built-in widgets:
Widget Description
Tk() Creates the main window.
Label Displays text or images.
Button Creates clickable buttons.
Entry Input text box (single-line).
Text Input text area (multi-line).
Frame Container to hold widgets.
Canvas For drawing shapes, images, and complex layouts.
Checkbutton Checkbox for multiple selections.
Radiobutton Radio button for single selection.
Listbox Displays a list of selectable items.
Scrollbar Adds scrolling functionality.
Spinbox Select values by incrementing/decrementing.
Menu Creates menu bars and dropdowns.
Scale Creates a slider for selecting values.
Progressbar Displays progress bars.

2. Geometry Managers (Widget Placement):


Tkinter provides three methods to arrange widgets:

pack() – Organizes widgets in blocks (top, bottom, left, right).


grid() – Arranges widgets in rows and columns (like a table).
place() – Places widgets at specific x, y coordinates.

3. Event Handling (Handling User Actions):


Tkinter uses an event-driven programming model where user actions (like button clicks, key
presses) trigger functions.

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.

Widgets (GUI Elements):


Tk() Widget:
The Tk() widget in Tkinter is the main application window that acts as a container for all other
widgets. It is the starting point of any Tkinter GUI application.
Syntax of Tk()
import tkinter as tk
root = tk.Tk() # Creating the main application window
root.mainloop() # Running the main event loop

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

Methods Associated with Tk() Widget:


The Tk() widget represents the main application window in Tkinter. It provides various
methods to control and manage the GUI.

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()

# Create main window


root = tk.Tk()
root.title("Tk() Methods Example")
root.geometry("400x300")

# Create buttons to trigger different methods


tk.Button(root, text="Change Title", command=change_title).pack(pady=5)
tk.Button(root, text="Change Size", command=change_size).pack(pady=5)
tk.Button(root, text="Change Background", command=change_bg_color).pack(pady=5)
tk.Button(root, text="Set Transparency", command=set_transparency).pack(pady=5)
tk.Button(root, text="Bring to Front", command=bring_to_front).pack(pady=5)
tk.Button(root, text="Send to Back", command=send_to_back).pack(pady=5)
tk.Button(root, text="Close Window", command=close_window, fg="red").pack(pady=5)

# Run the application


root.mainloop()

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")

# Create buttons to trigger different methods


tk.Button(root, text="Toggle Resizable", command=toggle_resizable).pack(pady=10)
tk.Button(root, text="Set Min Size (300x200)", command=set_min_size).pack(pady=10)
tk.Button(root, text="Set Max Size (800x600)", command=set_max_size).pack(pady=10)
tk.Button(root, text="Force Update", command=force_update).pack(pady=10)

# Run the application


root.mainloop()

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...)

master – Parent widget (usually a Tk() or Frame).


text – The text to display.
Additional options – Used for customizing the label (font, color, size, background, etc.)

1. Text and Font Options:


Option Description Example
font Sets the font style, size, and weight.
font=("Arial", 14, "bold")
fg or foreground Sets text color. fg="red" or foreground="blue"
bg or background Sets background color. bg="yellow" or
background="gray"
width Width of the label in characters. width=20
height Height of the label in lines (rarely height=3
used).
wraplength Wraps text after the given width (in wraplength=100
pixels).

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).

Example (Displaying an image):


photo = tk.PhotoImage(file="example.png")
label = tk.Label(root, image=photo)

3. Alignment and Positioning


Option Description Example
justify Justifies text (left, center, right). justify="center"
anchor Aligns text/image inside the label anchor="w"
(n, s, e, w, center).
padx, pady Adds padding inside the label padx=10, pady=5
(horizontal & vertical).

Example (Alignment & Padding):


label = tk.Label(root, text="Aligned Text", anchor="w", padx=10, pady=5)

4. Borders & Relief Styles:


Option Description Example
borderwidth Defines the border thickness. borderwidth=2
relief Border style (flat, raised, sunken, relief="solid"
solid, ridge, groove).

Example (Border Styling):


label = tk.Label(root, text="Border Example", borderwidth=2, relief="ridge")

5. Variable Binding (Dynamic Text Updates):


Option Description Example
textvariable Links label text to a StringVar(), textvariable=var
allowing dynamic updates.

Example (Dynamic Update with StringVar):


var = tk.StringVar()
var.set("Original Text")
label = tk.Label(root, textvariable=var)
var.set("Updated Text") # This will automatically update the label

6. Cursor & Mouse Events:


Option Description Example
cursor Changes the mouse cursor when cursor="hand2"
over the label.
takefocus Determines if the label can receive takefocus=True
focus.

Example (Clickable Label with Cursor Change):


label = tk.Label(root, text="Hover Me", cursor="hand2")

7. Other Advanced Options:


Option Description Example
state Defines whether the label is active state="disabled"
(normal) or disabled (disabled).
compound Positions text relative to an image compound="left"
(top, bottom, left, right).

Example (Image with Text on the Right):


label = tk.Label(root, text="Image Example", image=photo, compound="right")

Example: All Options Combined

import tkinter as tk

root = tk.Tk()
root.title("Tkinter Label Example")

# StringVar for dynamic text


text_var = tk.StringVar()
text_var.set("Dynamic Text")
# Load an image (Ensure you have an image file)
photo = tk.PhotoImage(file="example.png")

# Creating the Label


label = tk.Label(
root,
text="Hello, Tkinter!",
font=("Arial", 16, "bold"),
fg="white",
bg="blue",
padx=10,
pady=5,
borderwidth=3,
relief="ridge",
image=photo,
compound="left",
textvariable=text_var,
cursor="hand2",
anchor="w"
)
label.pack()

root.mainloop()

Output:
# can’t get o/p for my PC as image type should be PNG

Methods Associated with Label Widget:


Method Description
config(option=value) Updates label properties dynamically (e.g., text, color,
font).
cget(option) Retrieves the current value of a label option (e.g., text,
bg, fg).
update() Forces the label to refresh immediately.
after(ms, func) Calls a function after ms milliseconds.
bind(sequence, func) Binds an event (e.g., click, hover) to the label widget.
winfo_geometry() Returns the label's geometry (position and size).
winfo_height() / winfo_width() Returns the height and width of the label.
winfo_x() / winfo_y() Returns the X and Y coordinates of the label.

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")

# Create a Label widget


label = tk.Label(root, text="Click buttons to interact with me", font=("Arial", 14),
bg="yellow")
label.pack(pady=20)

# Create Buttons to trigger different methods


tk.Button(root, text="Update Label", command=update_label).pack(pady=5)
tk.Button(root, text="Show Label Text", command=show_text).pack(pady=5)
tk.Button(root, text="Change Font", command=change_font).pack(pady=5)
tk.Button(root, text="Delayed Change", command=delayed_change).pack(pady=5)
tk.Button(root, text="Change Color", command=change_color).pack(pady=5)
tk.Button(root, text="Bind Click Event", command=bind_click_event).pack(pady=5)
tk.Button(root, text="Show Label Geometry", command=show_geometry).pack(pady=5)

# Run the application


root.mainloop()

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.

1. Font Related Options:


Option Description
font Defines the font family, size, and style.
Example: font=("Arial", 12, "bold")
fg or foreground Text color.
Example: fg="white"
bg or background Background color of the button.
Example: bg="blue"

2. Size & Padding Options:


Option Description
width Width of the button (in character units).
Example: width=20
height Height of the button (in character units).
Example: height=2
padx Horizontal padding inside the button.
Example: padx=10

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

4. Border & Relief Options:


Option Description
bd or borderwidth Defines the border thickness. Example: bd=5

relief Defines button border style. Options: FLAT,


RAISED, SUNKEN, RIDGE, GROOVE.
Example: relief=tk.RAISED
bd or borderwidth Defines the border thickness. Example: bd=5

5. Image & Icon Options:


Option Description
image Displays an image on the button instead of text. Example:
image=my_image
compound Defines the position of text relative to an image (LEFT,
RIGHT, TOP, BOTTOM). Example:
compound=tk.LEFT

6. Anchor & Alignment Options:


Option Description
anchor Positions text inside the button: N, S, E, W, NE, SE,
NW, SW, CENTER. Example: anchor=tk.W
justify Aligns multiple lines of text (LEFT, CENTER,
RIGHT). Example: justify=tk.LEFT

Example 1: Simple Tkinter Button


import tkinter as tk

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()

Example 2: Button with Custom Styles


import tkinter as tk

def greet():
label.config(text="Hello, Tkinter!")

root = tk.Tk()
root.title("Styled Button")

label = tk.Label(root, text="Click the button", font=("Arial", 14))


label.pack(pady=10)

button = tk.Button(root, text="Greet", font=("Arial", 12, "bold"), fg="white", bg="blue",


padx=10, pady=5, command=greet)
button.pack(pady=10)

root.mainloop()

Output:

Example 3: Button with Images


import tkinter as tk
from PIL import Image, ImageTk # Requires Pillow library

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)

button = tk.Button(root, image=photo, command=clicked)


button.pack(pady=10)

label = tk.Label(root, text="")


label.pack()

root.mainloop()

Methods Associated with Button Widget in Tkinter


The Button widget in Tkinter provides various methods to modify its properties and behavior
dynamically.

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")

# Create a Button widget


button = tk.Button(root, text="Click Me", font=("Arial", 12), command=change_text)
button.pack(pady=10)
# Create Buttons to trigger different methods
tk.Button(root, text="Get Text", command=get_text).pack(pady=5)
tk.Button(root, text="Simulate Click", command=simulate_click).pack(pady=5)
tk.Button(root, text="Flash Button", command=flash_button).pack(pady=5)
tk.Button(root, text="Delayed Update", command=delayed_action).pack(pady=5)

# Run the application


root.mainloop()

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

# Create the main window


root = tk.Tk()
root.title("Button Widget Advanced Methods Example")
root.geometry("350x400")
# Tkinter variable for wait_variable()
var = tk.IntVar()

# Create a Button widget


button = tk.Button(root, text="Click Me", font=("Arial", 12))
button.pack(pady=10)

# Create Buttons to trigger different methods


tk.Button(root, text="Update Now", command=update_button).pack(pady=5)
tk.Button(root, text="Wait for Variable", command=wait_for_variable).pack(pady=5)
tk.Button(root, text="Change Variable", command=change_var).pack(pady=5)
tk.Button(root, text="Wait for Window Close", command=open_window).pack(pady=5)
tk.Button(root, text="Wait for Visibility", command=check_visibility).pack(pady=5)

# Run the application


root.mainloop()
Output:

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.

List of Available Options for Entry Widget:


Option Description
bg / background Sets the background color of the entry field.
fg / foreground Sets the text color inside the entry.
bd / borderwidth Defines the border thickness around the entry (default: 2).
cursor Changes the cursor style inside the entry (e.g., "arrow", "xterm").
exportselection If True, allows copying the selected text to the clipboard (default:
True).
font Specifies the font type, size, and style (e.g., ("Arial", 12, "bold")).
highlightbackground Background color of the highlight when the widget is not focused.
highlightcolor Color of the highlight when the widget is focused.
highlightthickness Thickness of the focus highlight border.
insertbackground Color of the cursor (text insertion point).
insertborderwidth Border width of the insertion cursor.
insertofftime Time (in ms) the cursor blinks off (default: 300).
insertontime Time (in ms) the cursor blinks on (default: 600).
insertwidth Width of the insertion cursor.
justify Sets text alignment ("left", "center", "right").
relief Defines the border style ("flat", "raised", "sunken", "ridge",
"solid", "groove").
selectbackground Background color of selected text.
selectborderwidth Border width of selected text.
selectforeground Foreground (text) color of selected text.
show Masks input (useful for passwords, e.g., show="*")
state Controls input state: "normal" (editable), "disabled" (non-
editable), "readonly" (read-only).
textvariable Links entry text to a Tkinter StringVar().
width Defines the width of the entry box in characters.
xscrollcommand Links an Entry widget to a horizontal scrollbar.
Option Description
bg / background Sets the background color of the entry field.
fg / foreground Sets the text color inside the entry.
bd / borderwidth Defines the border thickness around the entry (default: 2).
cursor Changes the cursor style inside the entry (e.g., "arrow", "xterm").
exportselection If True, allows copying the selected text to the clipboard (default:
True).
font Specifies the font type, size, and style (e.g., ("Arial", 12, "bold")).
highlightbackground Background color of the highlight when the widget is not focused.
highlightcolor Color of the highlight when the widget is focused.
highlightthickness Thickness of the focus highlight border.
insertbackground Color of the cursor (text insertion point).

Example:
import tkinter as tk

root = tk.Tk()
root.title("Entry Widget Options Example")

# StringVar to store entry text


text_var = tk.StringVar()

# Create an Entry widget with multiple options


entry = tk.Entry(root,
width=30,
font=("Arial", 14),
fg="blue",
bg="lightgray",
justify="center",
textvariable=text_var,
show="*") # Mask input (like password)
entry.pack(pady=10)
# Function to show entered text
def show_text():
print("Entered Text:", text_var.get())

# Button to get input text


button = tk.Button(root, text="Get Text", command=show_text)
button.pack(pady=5)

root.mainloop()

Methods associated with Entry Widget:


The Entry widget in Tkinter has several built-in methods that allow you to manipulate and
interact with the text inside it.

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()

# Create the main window


root = tk.Tk()
root.title("Entry Widget Methods Example")

# Create an Entry widget


entry = tk.Entry(root, width=30, font=("Arial", 14))
entry.pack(pady=10)
# Buttons to trigger methods
btn_get = tk.Button(root, text="Get Text", command=get_text)
btn_get.pack(pady=5)

btn_insert = tk.Button(root, text="Insert Text", command=insert_text)


btn_insert.pack(pady=5)

btn_delete = tk.Button(root, text="Delete Text", command=delete_text)


btn_delete.pack(pady=5)

btn_select = tk.Button(root, text="Select Text", command=select_text)


btn_select.pack(pady=5)

btn_clear = tk.Button(root, text="Clear Selection", command=clear_selection)


btn_clear.pack(pady=5)

# Run the application


root.mainloop()

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.")

# Create the main window


root = tk.Tk()
root.title("Entry Widget Methods Example")
root.geometry("400x300")

# Create an Entry widget with horizontal scrolling


entry = tk.Entry(root, width=30, font=("Arial", 12))
entry.pack(pady=10)
entry.insert(0, "This is a sample text for scrolling and testing.")

# Create Buttons to trigger different methods


tk.Button(root, text="Change Style", command=change_style).pack(pady=5)
tk.Button(root, text="Move Cursor", command=move_cursor).pack(pady=5)
tk.Button(root, text="Get Cursor Index", command=get_index).pack(pady=5)
tk.Button(root, text="Scroll to Start", command=scroll_to_start).pack(pady=5)
tk.Button(root, text="Scroll Right", command=scroll_right).pack(pady=5)
tk.Button(root, text="Set Focus", command=set_focus).pack(pady=5)
tk.Button(root, text="Check Selection", command=check_selection).pack(pady=5)

# Run the application


root.mainloop()

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.

Syntax of Text Widget


import tkinter as tk

root = tk.Tk()
text_widget = tk.Text(root, options...)
text_widget.pack()
root.mainloop()

• root → The main window.


• Text(root, options...) → Creates a Text widget with optional parameters.

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.

Methods Associated with the Text Widget:


The Text widget in Tkinter provides various methods to insert, retrieve, modify, delete, and
format text. Below are some commonly used methods:

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 main window


root = tk.Tk()
root.title("Text Widget Methods")
root.geometry("500x400")

# Create Text widget


text_widget = tk.Text(root, wrap="word", undo=True)
text_widget.pack(expand=True, fill="both")

# 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)
]

for text, command in buttons:


tk.Button(root, text=text, command=command).pack(side="top", padx=5, pady=2,
fill="x")

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.

Methods Associated with Frame Widget:


Method Description
config(options) Configures frame properties dynamically.
cget(option) Retrieves the current value of an option.
pack(**options) Packs the frame into the parent widget.
grid(**options) Places the frame in a grid layout.
place(**options) Places the frame at an absolute position.
destroy() Destroys the frame and all child widgets.
winfo_children() Returns a list of all child widgets inside the frame.
winfo_geometry() Gets the geometry details of the frame.
Method Description
config(options) Configures frame properties dynamically.
cget(option) Retrieves the current value of an option.
pack(**options) Packs the frame into the parent widget.

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 main window


root = tk.Tk()
root.title("Frame Widget Example")
root.geometry("400x400")

# Create Frame
frame = tk.Frame(root, width=200, height=150, bg="gray", relief="ridge", bd=5)
frame.pack(pady=20)

# Add widgets inside the frame


label = tk.Label(frame, text="Inside Frame", bg="gray", fg="white")
label.pack()

btn_change_bg = tk.Button(root, text="Change Background", command=change_bg)


btn_get_bg = tk.Button(root, text="Get Background", command=get_bg)
btn_destroy = tk.Button(root, text="Destroy Frame", command=destroy_frame)
btn_children = tk.Button(root, text="Show Children", command=show_children)
btn_geometry = tk.Button(root, text="Get Geometry", command=get_geometry)
btn_grid = tk.Button(root, text="Use Grid", command=use_grid)
btn_place = tk.Button(root, text="Use Place", command=use_place)
btn_pack = tk.Button(root, text="Use Pack", command=use_pack)

# 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)

master: The parent window (like Tk or Frame).


options: Various styling and functional options like bg, height, width, etc.

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").

Methods associated with Canvas Widget:


Method Description
create_arc(x1, y1, x2, y2, options) Creates an arc (part of an oval).
create_bitmap(x, y, options) Creates a bitmap image.
create_image(x, y, options) Displays an image on the canvas.
create_line(x1, y1, x2, y2, ..., options) Draws a line connecting the given coordinates.
create_oval(x1, y1, x2, y2, options) Draws an oval (or circle).
create_polygon(x1, y1, x2, y2, ..., Creates a polygon shape.
options)
create_rectangle(x1, y1, x2, y2, options) Creates a rectangle.
create_text(x, y, options) Adds text to the canvas.
create_window(x, y, options) Embeds another widget inside the canvas.
coords(item_id, x1, y1, x2, y2) Changes the coordinates of an existing shape.
move(item_id, dx, dy) Moves an item by the given offsets.
delete(item_id) Deletes an item from the canvas.
itemconfig(item_id, options) Modifies item properties like color, width, etc.
tag_bind(tag, event, function) Binds an event to an item with a specific tag.
tag_unbind(tag, event) Unbinds an event from an item.

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()

# Create various shapes and elements


arc = canvas.create_arc(50, 50, 150, 150, start=0, extent=150, fill="red")
bitmap = canvas.create_bitmap(200, 50, bitmap="error")
img = PhotoImage(width=50, height=50) # Creating an empty image for demo
image = canvas.create_image(300, 50, image=img)
line = canvas.create_line(10, 200, 200, 200, width=3, fill="black")
oval = canvas.create_oval(250, 100, 350, 200, fill="green")
polygon = canvas.create_polygon(50, 300, 150, 250, 200, 350, fill="orange",
tags="poly_tag")
rect = canvas.create_rectangle(100, 100, 200, 200, fill="purple")
text = canvas.create_text(250, 350, text="Hello Canvas!", font=("Arial", 16), fill="blue")

# Creating a window inside the canvas


btn = Button(root, text="Click Me")
canvas.create_window(400, 350, window=btn)

# Bind an event to the polygon


canvas.tag_bind("poly_tag", "<Button-1>", bind_event)

# Buttons to demonstrate different methods


btn_move = Button(root, text="Move Rectangle", command=move_rectangle)
btn_move.pack()

btn_color = Button(root, text="Change Color", command=change_color)


btn_color.pack()

btn_delete = Button(root, text="Delete Text", command=delete_text)


btn_delete.pack()

btn_update = Button(root, text="Update Oval Coords", command=update_coords)


btn_update.pack()

btn_unbind = Button(root, text="Unbind Polygon Event", command=unbind_event)


btn_unbind.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 main window


root = Tk()
root.title("Checkbutton Widget Demo")
root.geometry("300x300")

# IntVar to store Checkbutton state (1=checked, 0=unchecked)


var = IntVar()

# Create a Checkbutton
check = Checkbutton(root, text="Accept Terms", variable=var, command=show_status)
check.pack(pady=10)

# Label to display Checkbutton status


status_label = Label(root, text="Checked: 0")
status_label.pack()

# Buttons to demonstrate Checkbutton methods


Button(root, text="Toggle", command=toggle_check).pack(pady=5)
Button(root, text="Select", command=select_check).pack(pady=5)
Button(root, text="Deselect", command=deselect_check).pack(pady=5)
Button(root, text="Flash", command=flash_check).pack(pady=5)
Button(root, text="Get Text", command=get_text).pack(pady=5)
Button(root, text="Invoke", command=invoke_check).pack(pady=5)

# Label to display Checkbutton text


text_label = Label(root, text="Text: Accept Terms")
text_label.pack()

# Run the application


root.mainloop()

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)

• master: The parent window (e.g., Tk or Frame).


• options: Various properties to customize appearance and behavior.

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 main window


root = Tk()
root.title("Radiobutton Widget Demo")
root.geometry("300x300")

# IntVar to store Radiobutton state


var = IntVar(value=1) # Default 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)

# Label to display selection


selection_label = Label(root, text="Selected: 1")
selection_label.pack()

# Buttons to demonstrate Radiobutton methods


Button(root, text="Select Option 1", command=select_option1).pack(pady=5)
Button(root, text="Select Option 2", command=select_option2).pack(pady=5)
Button(root, text="Invoke Option 2", command=invoke_option).pack(pady=5)
Button(root, text="Get Selected Text", command=get_text).pack(pady=5)
Button(root, text="Change Option 1 Text", command=change_text).pack(pady=5)

# Label to display text of selected radiobutton


text_label = Label(root, text="Text: Option 1")
text_label.pack()

# Run the application


root.mainloop()

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)

• master: The parent widget (e.g., Tk() or Frame).


• options: Various properties to customize appearance and behavior.

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 main window


root = Tk()
root.title("Listbox Methods Demo")
root.geometry("300x350")

# Create Listbox
listbox = Listbox(root, selectmode="extended", width=25, height=10)
listbox.pack(pady=10)

# Add some initial items


for i in range(5):
listbox.insert(END, f"Item {i+1}")
# Buttons for demonstrating Listbox methods
Button(root, text="Add Item", command=add_item).pack(pady=5)
Button(root, text="Remove Selected", command=remove_selected).pack(pady=5)
Button(root, text="Get Selected", command=get_selected).pack(pady=5)
Button(root, text="Clear Selection", command=clear_selection).pack(pady=5)
Button(root, text="Activate First Item", command=activate_first).pack(pady=5)
Button(root, text="Select First Two Items", command=select_first_two).pack(pady=5)
Button(root, text="Check if 2nd Item Selected", command=check_selection).pack(pady=5)

# Run the application


root.mainloop()
Output:
Scrollbar:
The Scrollbar widget in Tkinter is used to add scrolling functionality to widgets like Listbox,
Text, and Canvas.

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.

Methods associated with Scrollbar:


Method Description
set(first, last) Updates the scrollbar position.
get() Returns the current position of the scrollbar.
yview() Moves the scrollbar vertically (used with Listbox, Canvas,
Text).
xview() Moves the scrollbar horizontally (used with Canvas, Text).
yview_moveto(fraction) Moves to a specific position (0.0 = top, 1.0 = bottom).
xview_moveto(fraction) Moves to a specific position (0.0 = left, 1.0 = right).
yview_scroll(number, what) Scrolls vertically (number of units or pages).
xview_scroll(number, what) Scrolls horizontally (number of units or pages).
config(option=value) Modifies properties such as color, size, etc.
Example:
from tkinter import Tk, Listbox, Scrollbar, Text, Canvas, RIGHT, Y, X, BOTH, END

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)

# Create main window


root = Tk()
root.title("Scrollbar Methods Demo")
root.geometry("400x400")

# Vertical Scrollbar for Listbox


list_scroll = Scrollbar(root, orient="vertical")
listbox = Listbox(root, yscrollcommand=list_scroll.set, height=5)
list_scroll.config(command=listbox.yview)

# Insert items into Listbox


for i in range(1, 51):
listbox.insert(END, f"Item {i}")

listbox.pack(side="left", fill="y")
list_scroll.pack(side="left", fill="y")

# Vertical Scrollbar for Text


text_scroll = Scrollbar(root, orient="vertical")
text = Text(root, yscrollcommand=text_scroll.set, height=5, width=40)
text_scroll.config(command=text.yview)

# Insert dummy text


text.insert(END, "Hello! Scroll this text up and down.\n" * 10)

text.pack(fill="both", expand=True)
text_scroll.pack(side=RIGHT, fill=Y)

# Horizontal Scrollbar for Canvas


canvas = Canvas(root, width=300, height=100, scrollregion=(0, 0, 1000, 100))
h_scroll = Scrollbar(root, orient="horizontal", command=canvas.xview)
canvas.config(xscrollcommand=h_scroll.set)

canvas.create_text(500, 50, text="Move this text using the horizontal scrollbar!",


font=("Arial", 12, "bold"))

canvas.pack(fill="both", expand=True)
h_scroll.pack(fill=X)

# Buttons to demonstrate Scrollbar methods


scroll_btn1 = Text(root, height=1, width=20)
scroll_btn1.insert(END, "Scroll to Bottom")
scroll_btn1.bind("<Button-1>", lambda e: scroll_to_bottom())
scroll_btn1.pack(pady=5)

scroll_btn2 = Text(root, height=1, width=20)


scroll_btn2.insert(END, "Scroll to Top")
scroll_btn2.bind("<Button-1>", lambda e: scroll_to_top())
scroll_btn2.pack(pady=5)

scroll_btn3 = Text(root, height=1, width=30)


scroll_btn3.insert(END, "Move Horizontal Scroll to Right")
scroll_btn3.bind("<Button-1>", lambda e: horizontal_scroll())
scroll_btn3.pack(pady=5)

# Run the application


root.mainloop()

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)

• master: The parent widget (e.g., Tk() or Frame).


• options: Various properties to customize the Spinbox.

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").

Methods associated with Spinbox:


Method Description
get() Returns the current value of the Spinbox.
set(value) Sets a specific value in the Spinbox.
configure(option=value) Modifies properties such as range, step size, etc.
focus_set() Sets focus to the Spinbox.
delete(start, end) Deletes text from the given index range.
insert(index, string) Inserts text at the specified position.

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 main window


root = Tk()
root.title("Spinbox Methods Demo")
root.geometry("300x250")

# Create a Spinbox
spinbox = Spinbox(root, from_=1, to=10, increment=1, wrap=True, width=10)
spinbox.pack(pady=10)

# Label to display selected value


label = Label(root, text="Selected: None", font=("Arial", 12))
label.pack(pady=5)

# Buttons to demonstrate Spinbox methods


Button(root, text="Show Value", command=show_value).pack(pady=5)
Button(root, text="Set Value to 5", command=set_value).pack(pady=5)
Button(root, text="Configure Spinbox (10-50, step 5)",
command=configure_spinbox).pack(pady=5)

# Run the application


root.mainloop()

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").

Methods associated with Menu Widget:


Method Description
add_command(label, Adds a menu item.
command, options)
add_separator() Adds a separator line between menu items.
add_cascade(label, menu) Creates a cascading menu (submenu).
delete(index1, index2) Deletes a menu item by index.
entryconfig(index, Modifies an existing menu item.
options)
index(label) Returns the index of a menu item.
invoke(index) Executes the command associated with a menu item.
post(x, y) Displays the menu at the specified screen coordinates.
unpost() Hides the menu.

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)

# Create main window


root = Tk()
root.title("Menu Widget Demo")
root.geometry("300x200")

# Create Menu Bar


menu_bar = Menu(root)

# Create File Menu


file_menu = Menu(menu_bar, tearoff=0)
file_menu.add_command(label="New", command=new_file)
file_menu.add_command(label="Open", command=open_file)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=exit_app)

# Add File Menu to Menu Bar


menu_bar.add_cascade(label="File", menu=file_menu)

# Create Edit Menu


edit_menu = Menu(menu_bar, tearoff=0)
edit_menu.add_command(label="Modify File Menu", command=modify_menu)
edit_menu.add_command(label="Delete Exit Item", command=delete_menu_item)

# Add Edit Menu to Menu Bar


menu_bar.add_cascade(label="Edit", menu=edit_menu)

# Configure Menu Bar


root.config(menu=menu_bar)

# Run the application


root.mainloop()

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").

Methods associated with Scale:


Method Description
get() Returns the current value of the Scale.
set(value) Sets the Scale to a specific value.
configure(option=value) Modifies properties such as range, step size, etc.
focus_set() Sets focus to the Scale.
coords() Returns the coordinates of the slider.

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)

# Create main window


root = Tk()
root.title("Scale Methods Demo")
root.geometry("300x300")

# Create a Scale widget


scale = Scale(root, from_=0, to=100, orient="horizontal", length=200)
scale.pack(pady=10)

# Label to display selected value


label = Label(root, text="Selected: None", font=("Arial", 12))
label.pack(pady=5)

# Buttons to demonstrate Scale methods


Button(root, text="Show Value", command=show_value).pack(pady=5)
Button(root, text="Set Value to 50", command=set_value).pack(pady=5)
Button(root, text="Configure Scale (10-200, step 10)",
command=configure_scale).pack(pady=5)

# Run the application


root.mainloop()
output:
Progressbar:
The Progressbar widget in Tkinter (provided by ttk) is used to show the progress of a task in a
graphical form.

Syntax:
from tkinter import ttk
progressbar = ttk.Progressbar(master, options)

• master: The parent widget (e.g., Tk() or Frame).


• options: Various properties to customize the Progressbar

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)

# Create main window


root = Tk()
root.title("Progressbar Methods Demo")
root.geometry("300x250")

# Create Progressbar widget


progressbar = ttk.Progressbar(root, orient="horizontal", length=200, mode="determinate")
progressbar.pack(pady=10)
# Buttons to demonstrate Progressbar methods
Button(root, text="Start", command=start_progress).pack(pady=5)
Button(root, text="Stop", command=stop_progress).pack(pady=5)
Button(root, text="Step by 10", command=step_progress).pack(pady=5)
Button(root, text="Set to 50%", command=set_progress).pack(pady=5)
Button(root, text="Get Progress Value", command=get_progress).pack(pady=5)
Button(root, text="Configure (Max 200, Length 300)",
command=configure_progress).pack(pady=5)

# Run the application


root.mainloop()
output:
A Brief Tour of Other GUIs:
As a proxy, we would like to present a single, simple GUI application written by using four of
the more popular toolkits: Tix (Tk Interface eXtensions), Pmw (Python MegaWidgets Tkinter
extension), wxPython (Python binding to wxWidgets), and PyGTK (Python binding to GTK+).
The final example demonstrates how to use Tile/Ttk—in both Python 2 and 3.

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()

ii). Python MegaWidgets (PMW)


Next we take a look at Python MegaWidgets. This module was created to address the aging
Tkinter. It basically helps to extend its longevity by adding more modern widgets to the GUI
palette.

Example-2 Pmw GUI Demo (animalPmw.pyw)


Our second example uses the Python MegaWidgets package.
1 #!/usr/bin/env python
2
3 from Tkinter import Button, END, Label, W
4 from Pmw import initialise, ComboBox, Counter
5
6 top = initialise()
7
8 lb = Label(top,
9 text='Animals (in pairs; min: pair, max: dozen)')
10 lb.pack()
11
12 ct = Counter(top, labelpos=W, label_text='Number:',
13 datatype='integer', entryfield_value=2,
14 increment=2, entryfield_validate={'validator':
15 'integer', 'min': 2, 'max': 12})
16 ct.pack()
17
18 cb = ComboBox(top, labelpos=W, label_text='Type:')
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()
iii). wxWidgets and wxPython
wxWidgets (formerly known as wxWindows) is a cross-platform toolkit that you can use to
build graphical user applications. It is implemented by using C++ and is available on a wide
range of platforms to which wxWidgets defines a consistent and common applications
programming interface (API).
The best part of all is that wxWidgets uses the native GUI on each platform, so your program
will have the same look-and-feel as all the other applications on your desktop. Another feature
is that you are not restricted to developing wxWidgets applications in C++; there are interfaces
to both Python and Perl.

Example-3 wxPython GUI Demo (animalWx.pyw)

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()

Related Modules and Other GUIs


There are other GUI development systems that can be used with Python. We present the
appropriate modules along with their corresponding window systems in bellow.

You might also like