Unit-3 Python QB Solved-Final
Unit-3 Python QB Solved-Final
p1 = Person()
Here, p1 is an instance (object) of the Person class.
9. How to return object from a method? Give example.
In Python, a method can return an object using the return statement.
The returned object can be stored and used later.
Example:
class Student:
def __init__(self, name):
[Link] = name
def create_student():
return Student("A")
Here, the method returns a Student object.
10. How to define private instance variables and methods in Python?
Private instance variables and methods are defined using double underscore ( __ ) before the name.
This process is called name mangling.
Example:
class Demo:
def __init__(self):
self.__value = 10
def __show(self):
print("Private Method")
These cannot be accessed directly outside the class.
11. What is multipath inheritance? Give example.
Multipath inheritance occurs when a class inherits from two classes having a common base class.
It creates multiple paths to reach the same base class.
Example:
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
Here, class D inherits from B and C, both derived from A.
12. What is purpose of super() method in inheritance?
The super() method is used to call the constructor or methods of the base class.
It helps derived classes access parent class properties and methods.
It avoids explicitly writing the base class name.
This makes the program more maintainable.
13. What is multiple inheritance? Write the syntax to derive multiple inheritance.
Multiple inheritance is a feature where a class inherits from more than one base class.
It allows a class to access properties and methods from multiple parent classes.
Syntax:
class DerivedClass(Base1, Base2):
pass
The derived class inherits features of both classes.
14. What is Polymorphism? List the different types of polymorphism in Python.
Polymorphism means one method or operator can perform different tasks in different situations.
It allows multiple classes to implement methods differently.
The types of polymorphism in Python are Method Overloading and Method Overriding.
Operator overloading is also a form of polymorphism.
15. Differentiate between method overloading and method overriding.
Same method name with different parameters Same method name and same parameters
Python uses default arguments for it Derived class changes base class method
Canvas Frame
Example Program
Hello
Welcome to Python
Output
Hello
Welcome to Python
Advantages of with Statement
• Automatically closes file
• No need to use close() manually
• Prevents file corruption
• Handles exceptions safely
• Cleaner and shorter code
Without with
f = open("[Link]", "r")
data = [Link]()
[Link]()
With with
[Link]()
Output
Line 1: Hello
Line 2: Good Morning
Line 3: How are you?
Explanation
• The file is opened in read mode.
• read() reads the entire file content at once.
• The content is stored in the variable content.
• Finally, the file is closed using close().
Advantages
• Simple and easy to use.
• Reads the complete file at once.
Disadvantage
• Not suitable for very large files because it consumes more memory.
2. readline() Method
The readline() method is used to read one line at a time from a file.
Syntax
file_handler.readline()
Each call to readline() reads the next line in the file.
Example
Assume [Link] contains:
Line 1: Hello
Line 2: Good Morning
Line 3: How are you?
Program:
f = open("[Link]", "r")
line1 = [Link]()
line2 = [Link]()
print(line1)
print(line2)
[Link]()
Output
Line 1: Hello
Line 2: Good Morning
Explanation
• readline() reads only one line at a time.
• The first call reads Line 1.
• The second call reads Line 2.
• It is useful when processing files line by line.
Advantages
• Suitable for reading large files.
• Saves memory by reading one line at a time.
3. readlines() Method
The readlines() method is used to read all lines of a file as a list.
Syntax
file_handler.readlines()
Each line becomes an item in the list.
Example
Assume [Link] contains:
Line 1: Hello
Line 2: Good Morning
Line 3: How are you?
Program:
f = open("[Link]", "r")
lines = [Link]()
print(lines)
[Link]()
Output
['Line 1: Hello\n',
'Line 2: Good Morning\n',
'Line 3: How are you?\n']
Explanation
• readlines() reads all lines together.
• It stores them as list elements.
• \n represents a newline character.
Advantages
• Useful when line-by-line access is needed.
• Easy to process using loops.
[Link] example , explain the different methods to write data to the file.
Python provides file handling features to store data permanently in files. To write data into a file, the file must be
opened in write mode ('w') or append mode ('a'). Python provides mainly two methods to write data to a file:
write() and writelines(). These methods are used to store text into files.
Syntax to Open a File for Writing
file_handler = open("[Link]", "w")
Where:
• "[Link]" → Name of the file
• "w" → Write mode
• file_handler → File object
1. write() Method
The write() method is used to write a string of data into a file. It writes one string at a time.
Syntax
file_handler.write(string)
• It writes the given string into the file.
• To move to the next line, \n must be used.
Example Program
f = open("[Link]", "w")
[Link]("Hello World\n")
[Link]("Welcome to Python\n")
[Link]()
Output (inside [Link])
Hello World
Welcome to Python
Explanation
• The file [Link] is opened in write mode ('w').
• The write() method writes text into the file.
• \n is used to create a new line.
• close() closes the file after writing.
Advantages of write()
• Used to write a single string at a time.
• Easy to use for small amounts of data.
Limitation
• Multiple write() statements are required for multiple lines.
2. writelines() Method
The writelines() method is used to write multiple lines of text to a file at once. It accepts a sequence (list) of strings.
Syntax
file_handler.writelines(sequence)
• The sequence contains multiple strings.
• \n should be included manually for line breaks.
Example Program
lines = [
"Hello World\n",
"Welcome to Python\n",
"File handling example\n"
]
f = open("[Link]", "w")
[Link](lines)
[Link]()
Output (inside [Link])
Hello World
Welcome to Python
File handling example
Explanation
• A list named lines contains multiple strings.
• The file is opened in write mode.
• writelines() writes all strings from the list into the file.
• Each string contains \n to create a new line.
Advantages of writelines()
• Writes multiple lines together.
• Reduces the need for multiple write() statements.
• Useful when handling large text data.
[Link] the different File attributes with example.
In Python, when a file is opened using the open() function, a file object is created. This file object contains several
attributes that provide information about the file such as file name, opening mode, and file status. These are called
file attributes. Python provides attributes like name, mode, and closed to get file-related information.
1. file_handler.name Attribute
The name attribute returns the name of the file that was opened.
Syntax
file_handler.name
Example
file_handler = open("[Link]", "w")
file_handler.close()
Output
File Name is [Link]
Explanation
• The file is opened in write mode.
• The name attribute returns the file name.
• It helps identify the file being accessed.
2. file_handler.mode Attribute
The mode attribute returns the access mode in which the file was opened.
Syntax
file_handler.mode
Example
file_handler = open("[Link]", "w")
file_handler.close()
Output
File Opening Mode is w
Explanation
• The file is opened in write mode (w).
• The mode attribute displays the file access mode.
• It helps to know whether the file is opened for reading, writing, or appending.
3. file_handler.closed Attribute
Definition
The closed attribute checks whether a file is closed or open.
It returns True if the file is closed and False otherwise.
Syntax
file_handler.closed
Example
file_handler = open("[Link]", "w")
file_handler.close()
print("File State after closing is", file_handler.closed)
Output
File State is False
File State after closing is True
Explanation
• Before closing, the file remains open, so it returns False.
• After calling close(), the file becomes closed and returns True.
• This helps verify whether the file is properly closed.
Program to Demonstrate File Attributes
file_handler = open("[Link]", "w")
file_handler.close()
Output
File Name is [Link]
File State is False
File Opening Mode is w
[Link] is a Class? With syntax and example, explain how a class is defined in Python.
A class is a collection of data members (variables) and member functions (methods) grouped together into a single
unit. It acts as a blueprint for creating objects.
In Python, a class is a blueprint or template used to create objects. A class defines the attributes (variables) and
methods (functions) that an object can have. It helps in organizing data and functions together into a single unit.
Python supports Object-Oriented Programming (OOP) using classes and objects.
Syntax for Defining a Class in Python
class ClassName:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
def method_name(self):
# method body
Explanation of Syntax
• class → Keyword used to define a class.
• ClassName → Name of the class.
• init() → Constructor method used to initialize object attributes.
• self → Refers to the current object of the class.
• Methods → Functions defined inside the class.
Steps to Define a Class in Python
1. Declare the Class
A class is declared using the class keyword.
Example:
class Person:
pass
Here, Person is the class name.
2. Define Constructor (__init__)
The constructor initializes object data.
Example:
def __init__(self, name, age):
[Link] = name
[Link] = age
3. Define Methods
Methods are used to define object behavior.
Example:
def display(self):
print([Link], [Link])
4. Create an Object
Objects are created using the class name.
Syntax:
object_name = ClassName(arguments)
Example Program to Define a Class in Python
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
person1 = Person()
print([Link])
print([Link])
Output
Unknown
0
Advantages of Constructor
1. Automatically initializes object data.
2. Reduces repeated code for assigning values.
3. Helps in creating objects with initial values.
4. Makes programs organized and easier to understand.
[Link] is inheritance? How to implement inheritance in Python? Give an example
Inheritance is one of the important concepts of Object-Oriented Programming (OOP) in Python. It allows a new
class to acquire the properties and methods of an existing class. The existing class is called the base class (parent
class) and the new class is called the derived class (child class). Inheritance helps in code reusability and reduces
duplication.
Types of Classes in Inheritance
1. Base Class (Parent Class)
The class whose properties and methods are inherited.
2. Derived Class (Child Class)
The class that inherits properties and methods from the base class.
Syntax of Inheritance in Python
class BaseClass:
# Base class definition
class DerivedClass(BaseClass):
# Derived class definition
Explanation of Syntax
• BaseClass → Parent class.
• DerivedClass(BaseClass) → Child class inherits from base class.
• The child class can add new methods or override existing methods.
How to Implement Inheritance in Python
Step 1: Define the Base Class
Create a parent class with variables and methods.
Step 2: Define the Derived Class
Create a child class by passing the parent class name inside parentheses.
Step 3: Use super() Method
Use super() to call the constructor of the base class.
Step 4: Create Object
Create an object of the derived class and access inherited methods.
Example Program of Inheritance
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display_info(self):
print(f"Name: {[Link]}, Age: {[Link]}")
class Employee(Person):
def __init__(self, name, age, employee_id):
# Call constructor of base class
super().__init__(name, age)
# Additional attribute
self.employee_id = employee_id
# Overriding method
def display_info(self):
super().display_info()
print(f"Employee ID: {self.employee_id}")
# Creating Employee object
employee = Employee("A", 28, "E12345")
class DerivedClass(BaseClass):
def __init__(self, derived_parameters, base_parameters):
super().__init__(base_parameters)
# Derived class constructor
Explanation
• super().init() calls the constructor of the superclass.
• It helps initialize attributes of the base class.
• The derived class can also define its own additional attributes.
2. Overriding Superclass Method
Method overriding is a feature where a derived class provides its own implementation of a method that already
exists in the superclass.
The derived class method must have:
• The same method name
• The same method signature
The super() function can be used to call the overridden superclass method.
Syntax
class BaseClass:
def method_name(self):
# Base class method
class DerivedClass(BaseClass):
def method_name(self):
super().method_name()
# Derived class method
Example Program: Overriding Superclass Constructor and Method
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display_info(self):
print(f"Name: {[Link]}, Age: {[Link]}")
class Employee(Person):
def __init__(self, name, age, employee_id):
# Calling superclass constructor
super().__init__(name, age)
class DerivedClass1(BaseClass):
# Inherits BaseClass
class DerivedClass2(DerivedClass1):
# Inherits DerivedClass1
Explanation of Syntax
• BaseClass → Parent class.
• DerivedClass1 → Inherits from BaseClass.
• DerivedClass2 → Inherits from DerivedClass1.
• The last class can access properties and methods of all previous classes.
Example Program of Multi-level Inheritance
class Person:
def __init__(self, name):
[Link] = name
def display_name(self):
print("Name:", [Link])
class Employee(Person):
def __init__(self, name, employee_id):
super().__init__(name)
self.employee_id = employee_id
def display_employee(self):
print("Employee ID:", self.employee_id)
class Manager(Employee):
def __init__(self, name, employee_id, department):
super().__init__(name, employee_id)
[Link] = department
def display_manager(self):
print("Department:", [Link])
class Base2:
def display2(self):
print("This is Base2 class")
class B(A):
# Derived from A
class C(A):
# Derived from A
class B(A):
def showB(self):
print("This is Class B")
class C(A):
def showC(self):
print("This is Class C")
# Creating object of D
obj = D()
# Calling methods
[Link]()
[Link]()
[Link]()
[Link]()
Output
This is Class A
This is Class B
This is Class C
This is Class D
Explanation of the Program
1. Base Class – A
• Class A is the common base class.
• It contains the method showA().
2. Derived Classes – B and C
• Class B inherits from A.
• Class C also inherits from A.
• Both classes access properties of class A.
3. Derived Class – D
• Class D inherits from both B and C.
class D(B, C):
• Thus, D receives properties through multiple paths.
4. Object Creation
An object of class D is created:
obj = D()
The object can access methods of A, B, C, and D.
Method Resolution Order (MRO)
Python resolves ambiguity in multipath inheritance using Method Resolution Order (MRO).
Syntax
[Link]()
Example
print([Link]())
The mro() method determines the order in which parent class methods are searched.
Advantages of Multipath Inheritance
1. Promotes code reusability.
2. Avoids duplication of code.
3. Allows sharing of common features among classes.
4. Helps in creating complex class relationships.
[Link] is Polymorphism? List the different types and explain any type with example
Polymorphism is one of the important concepts of Object-Oriented Programming (OOP) in Python. The word
“Poly” means many and “Morph” means forms. Polymorphism allows the same method or operator to behave
differently in different situations. It enables different classes to implement the same method in different ways.
Types of Polymorphism in Python
The different types of polymorphism in Python are:
1. Method Overloading
• Method overloading means defining multiple methods with the same name but different parameters.
• Python supports method overloading using default arguments.
2. Method Overriding
• Method overriding means a derived class provides its own implementation of a method already present in
the base class.
• The method name and signature remain the same.
3. Operator Overloading
• Operator overloading is a form of polymorphism where operators behave differently depending on
operands.
• It is implemented using magic methods like __add__().
Explain Method Overriding with Example
Method overriding is a type of polymorphism where a child class changes the implementation of a method that
already exists in the parent class.
The method in the derived class:
• Has the same name as the parent class method.
• Has the same method signature.
• Can extend or replace parent class functionality.
Example Program
class Person:
def display_info(self):
print("This is Person class")
class Employee(Person):
# Overriding method
def display_info(self):
print("This is Employee class")
# Creating object
employee = Employee()
# Calling method
employee.display_info()
Output
This is Employee class
Explanation of the Program
• The Person class is the base class containing the method display_info().
• The Employee class inherits from Person.
• The Employee class overrides the display_info() method by providing its own implementation.
• When the method is called using the object of Employee, the overridden method in the child class executes
instead of the parent class method.
Advantages of Polymorphism
1. Promotes code reusability.
2. Improves flexibility in programming.
3. Makes code easier to maintain.
4. Allows the same method name to perform different tasks.
[Link] method overloading and overriding with example .
Method overloading and method overriding are two important types of polymorphism in Python. Polymorphism
allows methods to perform different tasks with the same name. Method overloading means using the same method
name with different parameters, whereas method overriding means redefining a parent class method in the child
class. These concepts improve flexibility and code reusability.
1. Method Overloading
Method overloading is a feature in which multiple methods have the same name but different parameters.
In Python, method overloading is achieved using:
• Default arguments
• Variable-length arguments (*args)
Python does not support traditional method overloading directly like other languages.
Example Program of Method Overloading
class Addition:
def add(self, a=None, b=None, c=None):
if a != None and b != None and c != None:
print("Sum =", a + b + c)
elif a != None and b != None:
print("Sum =", a + b)
else:
print("Provide at least two numbers")
# Creating object
obj = Addition()
[Link](10, 20)
[Link](10, 20, 30)
Output
Sum = 30
Sum = 60
Explanation of the Program
• A class Addition is created with method add().
• The same method name is used for different numbers of arguments.
• If two values are passed, it adds two numbers.
• If three values are passed, it adds three numbers.
• Thus, the same method performs different operations.
Advantages of Method Overloading
1. Improves code readability.
2. Reduces the need for multiple method names.
3. Makes programs flexible.
2. Method Overriding
Method overriding is a feature in which a derived class redefines a method that already exists in the parent class.
In method overriding:
• Method name remains the same.
• Parameters remain the same.
• The child class provides a new implementation.
Example Program of Method Overriding
class Person:
def display(self):
print("This is Person class")
class Employee(Person):
# Overriding method
def display(self):
print("This is Employee class")
# Creating object
obj = Employee()
# Calling method
[Link]()
Output
This is Employee class
Explanation of the Program
• The Person class contains method display().
• The Employee class inherits from Person.
• The display() method is redefined in Employee class.
• When the method is called using Employee object, the child class method executes.
Advantages of Method Overriding
1. Allows modification of parent class behavior.
2. Supports runtime polymorphism.
3. Improves flexibility and extensibility.
[Link] the steps involved in creating a GUI application in Python with a suitable example.
A GUI (Graphical User Interface) application allows users to interact with a program through windows, buttons,
labels, text boxes, menus, etc. instead of typing commands. In Python, GUI applications are mainly developed using
the Tkinter module. Tkinter provides different widgets to design user-friendly applications.
Steps Involved in Creating a GUI Application in Python
The following steps are involved in creating a GUI application in Python:
Step 1: Import Tkinter Module
The first step is to import the Tkinter package, which provides GUI components.
Syntax
from tkinter import *
Explanation
• Tkinter contains classes and functions required for GUI programming.
• It provides widgets such as Button, Label, Entry, Frame, Canvas, Scrollbar, etc.
Step 2: Create the Root Window
The root window is the main window of the application. All widgets are placed inside this window.
Syntax
root = Tk()
Explanation
• Tk() creates the root window.
• It acts as the top-level container for widgets.
Step 3: Set Window Properties
After creating the root window, properties like title, size, and background color can be set.
Example
[Link]("My GUI Application")
[Link]("400x300")
[Link](bg="lightblue")
Explanation
• title() sets the window title.
• geometry() sets the size of the window.
• configure() sets background color.
Step 4: Add Widgets
Widgets are GUI components used for user interaction.
Examples:
• Label → Displays text
• Button → Performs action on click
• Entry → Takes user input
Example
label = Label(root, text="Welcome to Python")
button = Button(root, text="Click Me")
Step 5: Place Widgets in Window
Widgets must be arranged inside the window using pack(), grid(), or place() methods.
Example
[Link]()
[Link]()
Explanation
• pack() arranges widgets automatically.
• grid() arranges widgets in rows and columns.
• place() positions widgets using coordinates.
Step 6: Run the Application
Finally, the application is executed using mainloop().
Syntax
[Link]()
Explanation
• mainloop() keeps the GUI window open.
• It waits for user interaction like button clicks.
Example Program
from tkinter import *
# Display button
[Link]()
# Run application
[Link]()
Output
A GUI window appears containing a button named “My Button”.
When the user clicks the button, the message:
Button Clicked
is displayed.
[Link] the different widgets used in Python. Explain all the widgets with examples.
In Python, widgets are graphical components used in GUI (Graphical User Interface) applications to interact with
users. Widgets help in displaying information and taking input from users. Python mainly uses the Tkinter module to
create GUI applications. Tkinter provides several widgets such as Frame, Label, Button, Message, Text, Scrollbar,
Entry, Spinbox, Listbox, Canvas, etc.
1. Frame Widget
A Frame widget is used to group and organize other widgets inside a window.
Syntax
f = Frame(root, bg='yellow')
Example
from tkinter import *
root = Tk()
f = Frame(root, bg='yellow')
[Link]()
[Link]()
Explanation
• A Frame acts like a container.
• It helps organize widgets in GUI applications.
2. Label Widget
A Label widget is used to display constant text or images that cannot be modified.
According to the notes:
“A Label represents constant text that is displayed in the frame or container.”
Syntax
Lbl = Label(root,
text="Welcome to Python",
width=20,
height=2,
fg='blue',
bg='yellow')
Example
from tkinter import *
root = Tk()
[Link]()
Explanation
• Used for displaying static text.
• Content cannot be edited.
3. Button Widget
A Button widget is used to perform an action when clicked.
Syntax
Button(root,
text="Click",
command=function_name)
Example
from tkinter import *
root = Tk()
def click():
print("Button Clicked")
btn = Button(root,
text="Click Me",
command=click)
[Link]()
[Link]()
Explanation
• Executes an event when clicked.
• Uses command option to call a function.
4. Message Widget
A Message widget is used to display multi-line text in word-wrapped format.
According to the notes:
“The Message widget is used to display multi-line text in a non-editable, word-wrapped format.”
Syntax
m = Message(root,
text="This is a message",
width=200)
Example
from tkinter import *
root = Tk()
m = Message(root,
text="This is a message widget")
[Link]()
[Link]()
Explanation
• Displays multi-line text.
• Text is non-editable.
5. Text Widget
A Text widget is used for multi-line text editing and display.
According to the notes:
“The Text widget allows users to interactively edit, select, and manipulate text content.”
Syntax
t = Text(root,
width=20,
height=10)
Example
from tkinter import *
root = Tk()
t = Text(root,
width=20,
height=5)
[Link]()
[Link]()
Explanation
• Allows editing of text.
• Supports multiple lines.
6. Scrollbar Widget
A Scrollbar widget is used to scroll text or content in another widget such as Text or Listbox.
According to the notes:
“A scroll bar is useful to scroll the text in another widget.”
Syntax
v = Scrollbar(root,
orient=VERTICAL)
Example
from tkinter import *
root = Tk()
text = Text(root)
scroll = Scrollbar(root)
[Link](side=RIGHT, fill=Y)
[Link]()
[Link]()
Explanation
• Used for vertical or horizontal scrolling.
• Helps view large text content.
7. Entry Widget
An Entry widget is used to take single-line input from the user.
Syntax
e = Entry(root)
Example
from tkinter import *
root = Tk()
e = Entry(root)
[Link]()
[Link]()
Explanation
• Used for entering text such as names or passwords.
• Accepts only single-line input.
8. Spinbox Widget
A Spinbox widget allows users to select values using up and down arrows.
Syntax
s = Spinbox(root,
from_=1,
to=10)
Example
from tkinter import *
root = Tk()
s = Spinbox(root,
from_=1,
to=10)
[Link]()
[Link]()
Explanation
• Used to select values from a range.
• Provides increment and decrement buttons.
9. Listbox Widget
A Listbox widget displays a list of items from which users can make selections.
Syntax
lb = Listbox(root)
Example
from tkinter import *
root = Tk()
lb = Listbox(root)
[Link](1, "Python")
[Link](2, "Java")
[Link]()
[Link]()
Explanation
• Displays multiple items.
• Allows single or multiple selection.
root = Tk()
canvas = Canvas(root,
width=300,
height=200)
[Link]()
[Link]()
Explanation
• Used for drawing shapes and graphics.
• Supports lines, rectangles, circles, and images.
[Link] example, explain the following widgets :
i)Message
ii) Entry
iii) Spinbox
iv) Textbox
v) Label
vi) Checkbox
vii) Radiobutton
In Python, widgets are graphical components used in Tkinter GUI applications to display information and interact
with users. Widgets help users provide input and view output easily. The commonly used widgets are Message,
Entry, Spinbox, Textbox (Text widget), Label, Checkbox, and Radiobutton.
i) Message Widget
A Message widget is used to display multi-line text in a non-editable, word-wrapped format.
According to the notes:
“The Message widget is used to display multi-line text in a non-editable, word-wrapped format.”
Syntax
m = Message(root,
text="Message Text",
width=200)
Example
from tkinter import *
root = Tk()
m = Message(root,
text="Welcome to Python GUI Programming",
width=200)
[Link]()
[Link]()
Explanation
• Displays multi-line text.
• Text is non-editable.
• Automatically wraps long text.
root = Tk()
e = Entry(root)
[Link]()
[Link]()
Explanation
• Used to accept single-line text input.
• Commonly used for entering name, password, age, etc.
root = Tk()
s = Spinbox(root,
from_=1,
to=10)
[Link]()
[Link]()
Explanation
• Used to choose values from a fixed range.
• Provides increment and decrement buttons.
root = Tk()
t = Text(root,
width=20,
height=5)
[Link]()
[Link]()
Explanation
• Used for multi-line text input.
• Supports editing and formatting.
• Allows insertion of text using insert().
v) Label Widget
A Label widget is used to display constant text or images.
According to the notes:
“A Label represents constant text that is displayed in the frame or container.”
Syntax
lbl = Label(root,
text="Welcome")
Example
from tkinter import *
root = Tk()
lbl = Label(root,
text="Welcome to Python")
[Link]()
[Link]()
Explanation
• Displays static text.
• Text cannot be edited.
• Used for headings and instructions.
root = Tk()
c1 = Checkbutton(root,
text="Python")
[Link]()
[Link]()
Explanation
• Allows multiple selections.
• Used when users can select more than one choice.
root = Tk()
r1 = Radiobutton(root,
text="Male",
value=1)
r2 = Radiobutton(root,
text="Female",
value=2)
[Link]()
[Link]()
[Link]()
Explanation
• Allows only one selection at a time.
• Used for choosing one option among many.
[Link] a note on arranging Widgets in a frame using layout managers.
In Python Tkinter, widgets such as Button, Label, Entry, Text, and Frame must be arranged properly inside a window
or frame. Layout managers are used to control the positioning and arrangement of widgets in a GUI application.
Tkinter provides three layout managers: pack(), grid(), and place(). These layout managers help organize widgets
efficiently inside a frame or root window.
1. Pack Layout Manager
The pack() layout manager is used to arrange widgets automatically one after another either vertically or
horizontally.
It organizes widgets based on available space.
Syntax
[Link](option)
Common Options
• side=TOP → Places widget at top
• side=BOTTOM → Places widget at bottom
• side=LEFT → Places widget at left
• side=RIGHT → Places widget at right
• fill=X → Expands widget horizontally
• fill=Y → Expands widget vertically
Example Program
from tkinter import *
root = Tk()
frame = Frame(root)
[Link]()
[Link](side=LEFT)
[Link](side=LEFT)
[Link](side=LEFT)
[Link]()
Explanation
• A Frame widget is created.
• Three buttons are added inside the frame.
• pack(side=LEFT) arranges buttons horizontally.
• Widgets are automatically positioned.
Advantages
1. Easy to use.
2. Suitable for simple GUI layouts.
2. Grid Layout Manager
The grid() layout manager arranges widgets in the form of rows and columns, similar to a table.
Each widget is placed at a specific row and column position.
Syntax
[Link](row=value, column=value)
Example Program
from tkinter import *
root = Tk()
[Link]()
Explanation
• Labels and Entry widgets are arranged in rows and columns.
• row=0, column=0 places widget in first row and first column.
• grid() provides organized alignment.
Advantages
1. Best for forms and tables.
2. Provides proper alignment of widgets.
3. Place Layout Manager
The place() layout manager is used to position widgets at specific coordinates (x, y) inside a window.
It gives precise control over widget placement.
Syntax
[Link](x=value, y=value)
Example Program
from tkinter import *
root = Tk()
[Link]("300x200")
b1 = Button(root, text="Submit")
[Link](x=100, y=50)
[Link]()
Explanation
• The button is placed at x = 100 and y = 50 coordinates.
• Exact positioning is possible using place().
Advantages
1. Gives exact control of widget position.
2. Useful for customized GUI design.
[Link] the process of creating a Listbox widget with a suitable example. Also, explain different values
associated with selectmode options.
A Listbox widget in Python Tkinter is used to display a list of items from which the user can select one or more
items. It is useful when multiple choices need to be displayed in a GUI application. The selectmode option controls
how items are selected in the Listbox. Tkinter provides different selection modes such as SINGLE, BROWSE,
MULTIPLE, and EXTENDED.
Process of Creating a Listbox Widget
The following steps are involved in creating a Listbox widget:
Step 1: Import Tkinter Module
First, import the Tkinter package.
Syntax
from tkinter import *
Explanation
• Tkinter provides GUI widgets such as Listbox, Button, Label, etc.
Step 2: Create Root Window
The root window acts as the main window.
Syntax
root = Tk()
Explanation
• Tk() creates the main application window.
Step 3: Create Listbox Widget
Create the Listbox using Listbox() class.
Syntax
listbox_name = Listbox(root, selectmode=mode)
Explanation
• root → Parent window
• selectmode → Specifies selection type
Step 4: Insert Items into Listbox
Items are added using the insert() method.
Syntax
listbox_name.insert(index, item)
Example
[Link](1, "Python")
[Link](2, "Java")
[Link](3, "C++")
Explanation
• index → Position of item
• item → Item to display in Listbox
Step 5: Display Listbox
Use pack() or grid() method to display the Listbox.
Syntax
listbox_name.pack()
Step 6: Run the Application
Execute GUI using mainloop().
Syntax
[Link]()