0% found this document useful (0 votes)
2 views50 pages

Unit-3 Python QB Solved-Final

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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 views50 pages

Unit-3 Python QB Solved-Final

Mangalore University lecturers prescribed answers

Uploaded by

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

Unit-3 – Python (QB solved)

1. List file types supported by Python. Give example for each.


Python supports two types of files: Text files and Binary files.
Text files store textual data and examples include .txt, .py, .html, .csv.
Binary files store data in the form of bytes and examples include .jpg, .mp3, .mp4, .pdf, .docx.
Text files are easy to read, whereas binary files are not readable in text editors.
2. What is the difference between File access mode ‘w’ and ‘x’?
The ‘w’ mode is used to open a file for writing and deletes existing content if the file already exists.
If the file does not exist, it creates a new file.
The ‘x’ mode is used to create a new file only.
If the file already exists, ‘x’ mode gives an error instead of overwriting it.
3. Give the syntax of with statement to open the file.
The with statement is used to open a file and automatically closes it after use.
Its syntax is:
with open("filename", "mode") as file_handler:
# file operations
The keyword as stores the file object in a variable.
It helps in proper resource management.
4. List any two file object attributes and mention its purpose.
Two file object attributes are name and mode.
The file_handler.name attribute returns the name of the file.
The file_handler.mode attribute returns the mode in which the file is opened.
Another attribute is closed, which returns True if the file is closed.
5. What is use of seek() and tell() methods?
The seek() method is used to move the file pointer to a specific position in the file.
The tell() method returns the current position of the file pointer.
These methods help in accessing file content at different locations.
They are useful while reading and writing files.
6. What is self-variable? Give example.
The self variable refers to the current instance of the class in Python.
It is used to access instance variables and methods inside a class.
Example:
class MyClass:
def __init__(self, value):
[Link] = value
Here, [Link] refers to the object’s variable.
7. Write the syntax to define constructor in Python.
A constructor is a special method used to initialize object data.
In Python, the constructor is written using init() method.
Syntax:
class ClassName:
def __init__(self, parameters):
[Link] = value
It is automatically called when an object is created.
8. What is instantiation? Give example.
Instantiation means creating an object of a class.
When an object is created, the constructor is automatically executed.
Example:
class Person:
pass

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.

Method Overloading Method Overriding

Same method name with different parameters Same method name and same parameters

Occurs in same class Occurs in base and derived class

Python uses default arguments for it Derived class changes base class method

Example: add(a,b) and add(a,b,c) Child class redefines parent method

16. Write any two advantages of using GUI in Python.


GUI makes applications user-friendly and easy to use.
Users can interact using buttons, menus, and windows instead of commands.
It improves the appearance of applications.
Python uses the Tkinter module for GUI development.
17. What is root window? How is it created in Python?
The root window is the main window in a GUI application.
It acts as the top-level container for all widgets.
It is created using the Tk() class.
Example:
import tkinter as tk
root = [Link]()
18. What are Widgets? List any two widgets used in Python.
Widgets are graphical components used to interact with users in GUI applications.
They help in displaying information and taking input.
Examples of widgets are Button, Label, Entry, Text, Scrollbar.
Two commonly used widgets are Button and Label.
19. What is Canvas? How is it created in Python?
A Canvas is a widget used to draw shapes, lines, images, and graphics.
It acts as a drawing surface in GUI applications.
It is created using the Canvas() class.
Example:
canvas = [Link](root, width=400, height=300, bg="white")
20. Differentiate Canvas and Frame.

Canvas Frame

Used for drawing shapes and graphics Used to organize widgets

Supports lines, text, images Holds buttons, labels, etc.

Interactive drawing possible Used for layout management

Created using Canvas() Created using Frame()

21. How to add a scrollbar to a Text widget?


A scrollbar is added by creating a Scrollbar widget and connecting it to the Text widget.
The scrollbar controls text movement vertically or horizontally.
Example:
scroll = Scrollbar(root, command=[Link])
[Link](yscrollcommand=[Link])
It helps in scrolling large text content.
22. Differentiate Label and Text Widget.

Label Widget Text Widget

Displays static text Displays editable text

Single-line display Multi-line display

Content cannot be edited Content can be edited

No scrolling support Supports scrolling

23. What is an entry widget? How is it created?


An Entry widget is used to take single-line input from the user.
It is commonly used for entering names, passwords, etc.
It is created using the Entry() class.
Example:
entry = [Link](root)
24. What is a spin box widget? How is it created?
A Spinbox widget is used to select values using up and down arrows.
It allows users to choose values from a specific range.
It is created using the Spinbox() class.
Example:
spin = [Link](root, from_=1, to=10)
25. List the values that can be assigned to selectmode property of listbox.
The selectmode property controls how items are selected in a listbox.
The values are SINGLE, BROWSE, MULTIPLE, and EXTENDED.
SINGLE allows only one selection.
MULTIPLE and EXTENDED allow selecting multiple items.
Long Answers:
[Link] and explain various file opening modes with example
File opening modes specify how a file is to be opened (read, write, append, etc.) using the open() function.
Syntax of open()
file_handler = open("filename", "mode")
• filename → name/path of the file
• mode → operation to be performed
Various File Opening Modes
1. Read Mode ('r')
• Opens file for reading only
• File must exist, otherwise error occurs
Example:
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
Displays contents of the file
2. Write Mode ('w')
• Opens file for writing
• If file exists → content is erased
• If file does not exist → new file is created
Example:
f = open("[Link]", "w")
[Link]("Hello Python")
[Link]()
Output:
File will contain:
Hello Python

3. Append Mode ('a')


• Adds data at the end of file
• Does not remove existing content
• Creates file if not exists
Example:
f = open("[Link]", "a")
[Link]("\nNew Line Added")
[Link]()
Output:
Hello Python
New Line Added

4. Read and Write Mode ('r+')


• Allows both reading and writing
• File must exist
• File pointer starts at beginning
Example:
f = open("[Link]", "r+")
print([Link]())
[Link]("\nExtra Data")
[Link]()
Output:
Displays old content and adds new content

5. Write and Read Mode ('w+')


• Allows reading and writing
• Deletes existing content
• Creates file if not exists
Example:
f = open("[Link]", "w+")
[Link]("New Data")
[Link](0)
print([Link]())
[Link]()
Output:
New Data

6. Append and Read Mode ('a+')


• Allows reading and appending
• File pointer is at end initially
• Use seek(0) to read from beginning
Example:
f = open("[Link]", "a+")
[Link]("\nAdded Line")
[Link](0)
print([Link]())
[Link]()
Output:
Displays full file with appended content

7. Exclusive Creation Mode ('x')


• Creates a new file only
• Gives error if file already exists
Example:
f = open("[Link]", "x")
[Link]("Created using x mode")
[Link]()
[Link] example explain how ‘with’ statement is used to open and close files.
The with statement in Python is used to open a file and automatically close it after the operations are completed.
Need for with Statement
• Normally, we use open() and close() separately
• If we forget to close the file → resource leakage may occur
• with statement solves this problem by automatically closing the file
Syntax
with open("filename", "mode") as file_handler:
# statements
Explanation:
• open() → opens the file
• file_handler → file object
• with → creates a context manager
• File is automatically closed after block execution

Example Program

# Using with statement to read a file


with open("[Link]", "r") as f:
content = [Link]()
print(content)

Sample File Content ([Link])

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 vs With with

Without with

f = open("[Link]", "r")
data = [Link]()
[Link]()

With with

with open("[Link]", "r") as f:


data = [Link]()
[Link] the different methods to read data from the file with example.
In Python, files are used to store data permanently. To access the contents of a file, it must first be opened using the
open() function in read mode ('r'). Python provides different methods to read data from a file. The commonly used
methods are read(), readline(), and readlines(). These methods help retrieve data in different ways depending on
the requirement.
Syntax to Open a File
file_handler = open("[Link]", "r")
Where:
• "[Link]" → Name of the file
• "r" → Read mode
• file_handler → Variable that stores the file object
1. read() Method
The read() method is used to read the entire contents of a file at once and returns it as a string.
Syntax
file_handler.read([size])
• size is optional.
• If size is not specified, the complete file content is read.
Example
Assume [Link] contains:
Line 1: Hello
Line 2: Good Morning
Line 3: How are you?
Program:
f = open("[Link]", "r")
content = [Link]()
print(content)

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

print("File Name is", file_handler.name)

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

print("File Opening Mode is", file_handler.mode)

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

print("File State is", file_handler.closed)

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

print("File Name is", file_handler.name)


print("File State is", file_handler.closed)
print("File Opening Mode is", file_handler.mode)

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

# Create two Person objects


person1 = Person("A", 25)
person2 = Person("B", 30)

# Access and print object attributes


print("Person 1: Name -", [Link], ", Age -", [Link])
print("Person 2: Name -", [Link], ", Age -", [Link])
Output
Person 1: Name - A , Age - 25
Person 2: Name - B , Age - 30
[Link] how objects are created with syntax and example.
An object is an instance of a class that contains data and methods. It is created to access the properties and
behaviors defined inside a class.
In Python, an object is an instance of a class. A class acts as a blueprint, whereas an object is the actual entity
created from that blueprint. Objects contain data members (attributes) and methods (functions) that define the
state and behavior of the object. Multiple objects can be created from the same class, and each object can have
different values.
Syntax to Create an Object
To create an object, the class name is followed by parentheses, and required values are passed to the constructor.
Syntax
object_name = ClassName(arguments)
Where:
• object_name → Name of the object
• ClassName → Name of the class
• arguments → Values passed to the constructor
Example Program to Create Objects
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

# Create two Person objects


person1 = Person("A", 25)
person2 = Person("B", 30)

# Access and print object attributes


print("Person 1: Name -", [Link], ", Age -", [Link])
print("Person 2: Name -", [Link], ", Age -", [Link])
Output
Person 1: Name - A , Age - 25
Person 2: Name - B , Age - 30
Explanation of the Program
• A class named Person is defined with a constructor __init__().
• The constructor initializes name and age attributes.
• Two objects, person1 and person2, are created using the class name.
• Values are passed to the constructor during object creation.
• Object attributes are accessed using dot notation.
Example:
[Link]
[Link]
[Link] is Constructor? Explain how constructors are defined in Python with example.
A constructor in Python is a special method used to initialize the attributes of an object when an object is created.
It is automatically called when an object is instantiated from a class. Constructors help in assigning initial values to
object variables. In Python, the constructor method is called __init__()
Syntax to Define Constructor in Python
class ClassName:
def __init__(self, parameter1, parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2
Explanation of Syntax
• class → Keyword used to define a class.
• init() → Constructor method.
• self → Refers to the current instance of the class.
• parameter1, parameter2 → Values passed during object creation.
• [Link] = variable → Used to initialize object attributes.
How Constructor is Defined in Python
Step 1: Define a Class
A class is created using the class keyword.
Example:
class Person:
Step 2: Define the Constructor
The constructor is written using __init__() inside the class.
Example:
def __init__(self, name, age):
[Link] = name
[Link] = age
Step 3: Create Objects
When objects are created, the constructor is automatically called.
Example:
person1 = Person("A", 25)
Example Program of Constructor
class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

# Creating objects of the Person class


person1 = Person("A", 25)
person2 = Person("B", 30)

# Accessing object attributes


print("Person 1: Name -", [Link], ", Age -", [Link])
print("Person 2: Name -", [Link], ", Age -", [Link])
Output
Person 1: Name - A , Age - 25
Person 2: Name - B , Age - 30
Explanation of the Program
• A class named Person is created.
• The __init__() constructor initializes name and age attributes.
• Two objects, person1 and person2, are created.
• During object creation, values are passed to the constructor.
• Object attributes are accessed using dot notation ([Link], [Link]).
Constructor with Default Values
A constructor can also have default parameter values. If values are not provided, default values are used.
Example
class Person:
def __init__(self, name="Unknown", age=0):
[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")

# Accessing inherited method


employee.display_info()
Output
Name: A, Age: 28
Employee ID: E12345
Explanation of the Program
• A Person class is created as the base class with attributes name and age.
• A method display_info() is defined to display person details.
• An Employee class is created as the derived class using class Employee(Person):.
• The super().init(name, age) statement calls the constructor of the parent class.
• The Employee class adds a new attribute called employee_id.
• The method display_info() is overridden in the child class.
• An object named employee is created and the inherited method is called.
Advantages of Inheritance
1. Promotes code reusability.
2. Reduces code duplication.
3. Makes programs easier to maintain.
4. Supports method overriding and extension of features.
[Link] with example overriding superclass constructor and method .
In Python, inheritance allows a derived class to inherit properties and methods from a base class. Sometimes, the
derived class may need to modify the constructor or method of the superclass (base class) according to its own
requirements. This process is called overriding superclass constructor and method. Python uses the super()
function to access superclass constructor and methods.
1. Overriding Superclass Constructor
When a derived class defines its own constructor and also calls the constructor of the superclass using
super().__init__(), it is called overriding superclass constructor.
The super() function is used to invoke the base class constructor and initialize inherited attributes.
Syntax
class BaseClass:
def __init__(self, parameters):
# Base class constructor

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)

# Additional attribute in derived class


self.employee_id = employee_id

# Overriding superclass method


def display_info(self):
super().display_info()
print(f"Employee ID: {self.employee_id}")

# Creating object of derived class


employee = Employee("A", 28, "E12345")

# Calling overridden method


employee.display_info()
Output
Name: A, Age: 28
Employee ID: E12345
Explanation of the Program
Superclass (Base Class)
• The Person class is the superclass.
• It contains attributes name and age.
• The method display_info() displays person details.
Overriding Superclass Constructor
• The Employee class inherits from Person.
• The constructor in the Employee class overrides the superclass constructor.
• super().__init__(name, age) calls the constructor of the Person class.
• This initializes inherited attributes name and age.
Overriding Superclass Method
• The method display_info() in Employee class overrides the method in Person class.
• super().display_info() calls the superclass method first.
• Then the Employee class displays employee_id.
Object Creation
• An object named employee is created from Employee class.
• Calling employee.display_info() executes the overridden method.
Advantages of Overriding
1. Helps in modifying parent class behavior in child class.
2. Provides code reusability through inheritance.
3. Allows adding extra functionality in derived classes.
4. Makes programs more flexible and maintainable.

[Link] is multi-level inheritance ? Explain with example.


Multi-level inheritance is a type of inheritance in Python where a class inherits from another derived class. In this
type, one class acts as a base class for another class, creating a chain of inheritance. This allows properties and
methods to be inherited across multiple levels. Multi-level inheritance helps in code reusability and reduces
repetition.
In this inheritance:
• One class acts as the base class.
• Another class becomes the derived class.
• A third class inherits from the derived class.
Thus, inheritance happens in multiple levels, forming a chain.
Syntax of Multi-level Inheritance
class BaseClass:
# Base class body

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

# Creating object of Manager class


m = Manager("A", "E101", "HR")

# Accessing methods of all classes


m.display_name()
m.display_employee()
m.display_manager()
Output
Name: A
Employee ID: E101
Department: HR
Explanation of the Program
1. Base Class – Person
• The Person class is the base class.
• It contains an attribute name and method display_name().
2. Derived Class – Employee
• The Employee class inherits from Person.
• It adds a new attribute employee_id.
• super().__init__(name) calls the constructor of Person class.
3. Derived Class – Manager
• The Manager class inherits from Employee.
• It adds a new attribute department.
• It inherits properties from both Employee and Person classes.
4. Object Creation
• An object m is created for the Manager class.
• Since Manager inherits from Employee and Person, it can access methods of all classes.
Advantages of Multi-level Inheritance
1. Promotes code reusability.
2. Reduces code duplication.
3. Makes programs more organized.
4. Allows hierarchical representation of real-world relationships.
[Link] example explain multiple inheritance in Python .
Multiple inheritance is a feature in Python where a class can inherit attributes and methods from more than one
parent class. It allows a derived class to access the features of multiple base classes. In Python, multiple inheritance
is achieved by specifying more than one parent class inside parentheses while defining the derived class. This
concept improves code reusability and reduces duplication.
Syntax of Multiple Inheritance
class DerivedClassName(Base1, Base2, ...):
# Class body
Explanation of Syntax
• Base1, Base2 → Parent classes.
• DerivedClassName → Child class inheriting from multiple classes.
• The derived class can access methods and attributes of all base classes.
Example Program of Multiple Inheritance
class Base1:
def display1(self):
print("This is Base1 class")

class Base2:
def display2(self):
print("This is Base2 class")

class Derived(Base1, Base2):


def display3(self):
print("This is Derived class")

# Creating object of Derived class


obj = Derived()

# Accessing methods of base and derived classes


obj.display1()
obj.display2()
obj.display3()
Output
This is Base1 class
This is Base2 class
This is Derived class
Explanation of the Program
1. Base Classes
• Base1 class contains method display1().
• Base2 class contains method display2().
2. Derived Class
• The Derived class inherits from both Base1 and Base2 using:
class Derived(Base1, Base2):
• It also defines its own method display3().
3. Object Creation
• An object obj of the Derived class is created.
obj = Derived()
4. Accessing Methods
• The object can access methods of both base classes and the derived class.
obj.display1()
obj.display2()
obj.display3()
This shows that the derived class inherits features from multiple parent classes.

Method Resolution Order (MRO)


In multiple inheritance, Python follows Method Resolution Order (MRO) to determine the order in which base
classes are searched for methods.
Syntax to Find MRO
class_name.mro()
Example:
print([Link]())
MRO helps Python decide which parent class method should be executed first.
Advantages of Multiple Inheritance
1. Promotes code reusability.
2. Allows combining features of multiple classes.
3. Reduces duplication of code.
4. Makes programs more flexible and efficient.
[Link] multipath inheritance with example.
Multipath inheritance is a type of inheritance in Python where a class inherits from two or more classes that have
a common base class. In this type of inheritance, there are multiple paths to inherit properties from the same base
class. Multipath inheritance may lead to ambiguity, which Python resolves using Method Resolution Order (MRO).
In this inheritance:
• One base class exists.
• Two or more classes inherit from the same base class.
• Another class inherits from these derived classes.
Thus, there are multiple paths to reach the same base class, so it is called multipath inheritance.
Syntax of Multipath Inheritance
class A:
# Base class

class B(A):
# Derived from A

class C(A):
# Derived from A

class D(B, C):


# Derived from B and C
Example Program of Multipath Inheritance
class A:
def showA(self):
print("This is Class A")

class B(A):
def showB(self):
print("This is Class B")

class C(A):
def showC(self):
print("This is Class C")

class D(B, C):


def showD(self):
print("This is Class D")

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

Suitable Example Program of GUI Application


from tkinter import *

# Step 1: Create root window


root = Tk()

# Step 2: Set window title and size


[Link]("GUI Application")
[Link]("300x200")

# Step 3: Create Label widget


lbl = Label(root, text="Welcome to Python",
font=("Courier", 16, "bold"),
fg="blue")

# Step 4: Create Button widget


btn = Button(root, text="Click Me",
width=15, height=2,
bg="yellow", fg="red")

# Step 5: Display widgets


[Link]()
[Link]()

# Step 6: Run application


[Link]()
Output
A GUI window appears with:
• A label displaying “Welcome to Python”
• A button named “Click Me”
[Link] to create a button widget and bind it to the event handler? Explain with example.
A Button widget in Python Tkinter is used to perform an action when the user clicks on it. Buttons help users
interact with the GUI application. To perform a specific task when a button is clicked, the button is connected to an
event handler using the command option. An event handler is a function that executes automatically when an
event occurs, such as clicking a button.
Syntax to Create a Button Widget
button_name = Button(parent_window,
text="Button Name",
width=value,
height=value,
bg="background color",
fg="foreground color",
command=function_name)
Explanation of Syntax
• parent_window → Parent container (root or frame).
• text → Text displayed on button.
• width and height → Size of button.
• bg → Background color.
• fg → Foreground (text) color.
• command → Binds button to event handler function.
Steps to Create a Button Widget and Bind it to Event Handler
Step 1: Import Tkinter Module
Import Tkinter package for GUI programming.
from tkinter import *
Step 2: Create Root Window
Create the main window.
root = Tk()
Step 3: Define Event Handler Function
Create a function that executes when button is clicked.
def buttonClick():
print("Button Clicked")
This function acts as the event handler.
Step 4: Create Button Widget
Create a button and bind it to the event handler using command option.
b = Button(root,
text="My Button",
width=15,
height=2,
bg="yellow",
fg="blue",
activebackground="green",
activeforeground="red",
command=buttonClick)
Explanation
• text → Displays button text.
• activebackground → Background color when button is clicked.
• activeforeground → Text color when clicked.
• command=buttonClick → Binds button to event handler.
Important:
Do not use parentheses after function name.
Correct:
command=buttonClick
Wrong:
command=buttonClick()
Step 5: Display Button Widget
Use pack() method to display the button.
[Link]()
Step 6: Run the Application
Execute the GUI using mainloop().
[Link]()

Example Program
from tkinter import *

# Create root window


root = Tk()

[Link]("Button Widget Example")


[Link]("300x200")

# Event handler function


def buttonClick():
print("Button Clicked")

# Create Button widget


b = Button(root,
text='My Button',
width=15,
height=2,
bg='yellow',
fg='blue',
activebackground='green',
activeforeground='red',
command=buttonClick)

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

lbl = Label(root, text="Welcome to Python")


[Link]()

[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](END, "Welcome to Python")

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

10. Canvas Widget


A Canvas widget is used to draw graphics, shapes, and images.
Syntax
canvas = Canvas(root,
width=300,
height=200)
Example
from tkinter import *

root = Tk()

canvas = Canvas(root,
width=300,
height=200)

canvas.create_line(10, 10, 200, 100)

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

ii) 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 to accept single-line text input.
• Commonly used for entering name, password, age, etc.

iii) 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 choose values from a fixed range.
• Provides increment and decrement buttons.

iv) Textbox (Text Widget)


A Text widget (Textbox) is used to display and edit multi-line text.
According to the notes:
“The Text widget allows users to interactively edit, select, and manipulate text content.”
Syntax
t = Text(root,
width=20,
height=5)
Example
from tkinter import *

root = Tk()

t = Text(root,
width=20,
height=5)

[Link](END, "Welcome to Python")

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

vi) Checkbox Widget


A Checkbox widget is used when the user can select one or more options.
In Tkinter, checkbox is created using the Checkbutton() widget.
Syntax
c = Checkbutton(root,
text="Option")
Example
from tkinter import *

root = Tk()

c1 = Checkbutton(root,
text="Python")
[Link]()

[Link]()
Explanation
• Allows multiple selections.
• Used when users can select more than one choice.

vii) Radiobutton Widget


A Radiobutton widget is used when the user can select only one option from multiple choices.
Syntax
r = Radiobutton(root,
text="Option",
value=1)
Example
from tkinter import *

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

b1 = Button(frame, text="Button 1")


b2 = Button(frame, text="Button 2")
b3 = Button(frame, text="Button 3")

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

Label(root, text="Name").grid(row=0, column=0)


Entry(root).grid(row=0, column=1)

Label(root, text="Age").grid(row=1, column=0)


Entry(root).grid(row=1, column=1)

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

Suitable Example Program


from tkinter import *

# Create root window


root = Tk()
[Link]("Listbox Example")
[Link]("300x200")
# Create Listbox widget
lb = Listbox(root, selectmode=SINGLE)
# Insert items
[Link](1, "Python")
[Link](2, "Java")
[Link](3, "C++")
[Link](4, "JavaScript")
# Display Listbox
[Link]()
# Run application
[Link]()
Output
A GUI window appears displaying a list of items:
• Python
• Java
• C++
• JavaScript
The user can select items based on the selectmode option.

Different Values Associated with selectmode Option


The selectmode property determines how items are selected in a Listbox.
1. SINGLE
Allows the user to select only one item at a time.
Syntax
selectmode=SINGLE
Example
lb = Listbox(root, selectmode=SINGLE)
Explanation
• Only one item can be selected.
• Selecting another item deselects the previous one.
2. BROWSE
Allows selecting one item, but the selection changes automatically when the mouse is dragged.
Syntax
selectmode=BROWSE
Example
lb = Listbox(root, selectmode=BROWSE)
Explanation
• Only one item is selected at a time.
• Moving the mouse changes the selected item.
3. MULTIPLE
Allows the user to select multiple items independently.
Syntax
selectmode=MULTIPLE
Example
lb = Listbox(root, selectmode=MULTIPLE)
Explanation
• Multiple items can be selected.
• Clicking items selects or deselects them.
4. EXTENDED
Allows selecting multiple items using mouse drag or Shift/Ctrl keys.
Syntax
selectmode=EXTENDED
Example
lb = Listbox(root, selectmode=EXTENDED)
Explanation
• Supports multiple selection.
• Users can use Shift or Ctrl keys for selection.

You might also like