Chapter Four1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

Chapter Four

Advanced Topics
Object oriented Programming
Object-oriented programming (OOP) is a method of structuring a program by bundling related
properties and behaviors into individual objects.
Object-oriented programming is based on the imperative programming paradigm, which uses
statements to change a program's state. It focuses on describing how a program should operate.
Examples of imperative programming languages are C, C++, Java, Go, Ruby and Python.
OOP uses the concept of objects and classes. A class can be thought of as a 'blueprint' for
objects. These can have their own attributes (characteristics they possess), and methods (actions
they perform).

An object has the following two characteristics:


 Attribute
 Behavior

For example, A Car is an object, as it has the following properties:


 name, price, color as attributes
 breaking, acceleration as behavior

One important aspect of OOP in Python is to create reusable code using the concept of
inheritance. This concept is also known as DRY (Don't Repeat Yourself).

Class and Objects


A class is a blueprint for the object. To create an object we require a model or plan or blueprint
which is nothing but class.
A class contains the properties (attribute) and action (behavior) of the object. Properties represent
variables, and the methods represent actions. Hence class includes both variables and methods.
You define a class by using the class keyword followed by a class name and a colon.
Syntax:
class Car:
#class body
Object is an instance of a class. The physical existence of a class is nothing but an object. In
other words, the object is an entity that has a state and behavior. It may be any real-world object
like the mouse, keyboard, laptop, etc.

Every object has the following properties.


 Identity: Every object must be uniquely identified.
 State: An object has an attribute that represents a state of an object, and it also reflects
the property of an object.
 Behavior: An object has methods that represent its behavior.

The object is created using the class name. When we create an object of the class, it is called
instantiation.

Class Attributes
In Class, attributes can be defined into two parts:

 Instance variables: The instance variables are attributes attached to an instance of a


class. We define instance variables in the constructor ( the __init__() method of a
class).
 Class Variables: A class variable is a variable that is declared inside of class, but outside
of any instance method or __init__() method.
Objects do not share instance attributes. Instead, every object has its copy of the instance
attribute and is unique to each object.

All instances of a class share the class variables. However, unlike instance variables, the value of
a class variable is not varied from object to object. Only one copy of the static variable will be
created and shared between all objects of the class.
Accessing properties and assigning values
 An instance attribute can be accessed or modified by using the dot notation:
instance_name.attribute_name.
 A class variable is accessed or modified using the class name

Example 2:
#accessing class and instance variable
class person:
age=7
def __init__(self,name):
self.name=name
def display(self):
print("this is a class with out __init__()")
print("i am",self.name,"and i am ",person.age, "years")
y = person("hana")
print(y.age)
y.display()
y.name="dawit"
person.age=15
y.display()

Class Methods
Inside a Class, we can define the following three types of methods.

 Instance method: Used to access or modify the object state. If we use instance
variables inside a method, such methods are called instance methods.
 Class method: Used to access or modify the class state. In method implementation, if we
use only class variables, then such type of methods we should declare as a class method.
 Static method: It is a general utility method that performs a task in isolation. Inside this
method, we don’t use instance or class variable because this static method doesn’t have
access to the class attributes.

A constructor is a special method used to create and initialize an object of a class. This method is
defined in the class.
The constructor will be executed automatically when the object is created. If we create three
objects, the constructor is called three times and initializes each object.

The main purpose of the constructor is to declare and initialize instance variables. It can take at
least one argument that is self. The __init()__ method is called the constructor in Python. In
other words, the name of the constructor should be __init__(self).

In Python, we have the following three types of constructors.


 Default Constructor
 Non-parametrized constructor
 Parameterized constructor
Default Constructor
A constructor is optional, and if we do not provide any constructor, then Python provides the
default constructor. Every class in Python has a constructor, but it's not required to define it.

#class without constructor but default is used


class person:
age=7
def display(self):
print("this is a class with out __init__()")
y = person()
print(y.age)
y.display()

Non-Parametrized Constructor
A constructor without any arguments is called a non-parameterized constructor. This type of
constructor is used to initialize each object with default values.
This constructor doesn’t accept the arguments during object creation. Instead, it initializes every
object with the same set of values.
#class with non-parameterized constructor
class person:
def __init__(self):
self.name="Abebe"
self.age=15
def display(self):
print("this is a class with non parametrized constructor( __init__(self))")
print(f'Name: {self.name} Age:{self.age}')
y = person()
y.display()

Parameterized Constructor
A constructor with defined parameters or arguments is called a parameterized constructor. We
can pass different values to each object at the time of creation using a parameterized constructor.
The first parameter to constructor is self that is a reference to the being constructed, and the rest
of the arguments are provided by the programmer. A parameterized constructor can have any
number of arguments.
#class with non-parameterized constructor
class person:
def __init__(self,nn,a):
self.name=nn
self.age=a
def display(self):
print("this is a class with parametrized constructor( __init__(self,name,age))")
print(f'Name: {self.name} Age:{self.age}')
O1 = person("sara",20)
N="kebede"
A=30
O2=person(N,A)
O1.display()
O2.display()
If we try to create an object from parameterized constructor like the following statement,
Ob=person( ) Error will be displayed

Traceback (most recent call last):


File "<string>", line 8, in <module>
TypeError: person.__init__() missing 2 required positional arguments: 'nn' and 'a'

Constructor With Default Values


Python allows us to define a constructor with default values. The default value will be used if we
do not pass arguments to the constructor at the time of object creation.

#constructor having default values


class person:
def __init__(self,nn,a=20,add="DB"):
self.name=nn
self.age=a
self.address=add
def display(self):
print("this is a class with defult valued constructor( __init__(self,name,age))")
print(f'Name: {self.name} Age:{self.age} Address: {self.address}')
O1 = person("sara",20) #for address it use DB
N="kebede"
O2=person(N) #for address and age it use DB and 20
O1.display()
O2.display()

Constructor overloading is a concept of having more than one constructor with a different
parameters list in such a way so that each constructor can perform different tasks.
Python does not support constructor overloading. If we define multiple constructors then, the
interpreter will considers only the last constructor and throws an error if the sequence of the
arguments doesn’t match as per the last constructor.

In Python, the constructor does not return any value. Therefore, while declaring a constructor, we
don’t have anything like return type. Instead, a constructor is implicitly called at the time of
object instantiation. Thus, it has the sole purpose of initializing the instance variables.
Python Destructors to Destroy the Object
Destructor is a special method that is called when an object gets destroyed. On the other hand, a
constructor is used to create and initialize an object of a class.
A destructor is called when an object is deleted or destroyed. Destructor is used to perform
the clean-up activity before destroying the object, such as closing database connections or file
handle.
Python has a garbage collector that handles memory management automatically. For example, it
cleans up the memory when an object goes out of scope.

The destructor is the reverse of the constructor. The constructor is used to initialize objects,
while the destructor is used to delete or destroy the object that releases the resource occupied by
the object.

In Python, destructor is not called manually but completely automatic. destructor gets called in
the following two cases
 When an object goes out of scope or
 The reference counter of the object reaches 0.
In Python, The special method __del__() is used to define a destructor. For example, when we
execute del object_name destructor gets called automatically and the object gets garbage
collected.
#using destructor to delete object and object property
class person:
def __init__(self,nn,a=20,add="DB"):
self.name=nn
self.age=a
self.address=add
def display(self):
print("this is a class with defult valued constructor( __init__(self,name,age))")
print(f'Name: {self.name} Age:{self.age} Address: {self.address}')
def __del__(self):
print('this is destructor')
print('Object destroyed')
O1 = person("sara",20)
N="kebede"
O2=person(N)
O1.display()
O2.display()
del O1
del O2.address
If we try to use an object O1.display() which destroyed it will return error
Traceback (most recent call last):
File "<string>", line 20, in <module>
NameError: name 'O1' is not defined

Encapsulation
Encapsulation in Python describes the concept of bundling data and methods within a single
unit. A class is an example of encapsulation as it binds all the data members (instance variables)
and methods into a single unit.
Using encapsulation, we can hide an object’s internal representation from the outside. This is
called information hiding.

Encapsulation is a way to can restrict access to methods and variables from outside of class.
Whenever we are working with the class and dealing with sensitive data, providing access to all
variables used within the class is not a good choice.
Encapsulation can be achieved by declaring the data members and methods of a class either as
private or protected. But In Python, we don’t have direct access modifiers like public, private,
and protected. We can achieve this by using single underscore and double underscores.

Access modifiers limit access to the variables and methods of a class. Python provides three
types of access modifiers private, public, and protected.

 Public Member: Accessible anywhere from outside of class (No underscore)


 Private Member: Accessible within the class (Double underscore)
 Protected Member: Accessible within the class and its sub-classes (single Underscore)
#Acces modifier Exercise
class person:
def __init__(self,name,_age):
self.Name=name
self._Age=_age
self.__salary=1500
class Employee(person):
def emp_info(self,win):
self.Win=win
def display(self):
print(f"Name: {self.Name}")
print(f"Name: {self._Age}")
print(f"Work_in: {self.Win}")
E1=Employee("hana",25)
E1.emp_info("harar")
E1.display()
Based the above example name is public and can be public access, age is protected and accessed
by only child class, salary is private and it cannot be accessed outside of person class. The
private members are accessed indirectly through Setter (mutator) and Getter (acutor)
The primary purpose of using getters and setters in object-oriented programs is to ensure data
encapsulation. Use the getter method to access data members and the setter methods to modify
the data members.

Advantages of Encapsulation
 Security: The main advantage of using encapsulation is the security of the data.
Encapsulation protects an object from unauthorized access. It allows private and protected
access levels to prevent accidental data modification.
 Data Hiding: The user would not know what is going on behind the scene. They would
only know that to modify a data member, call the setter method. To read a data member, call
the getter method. What these setter and getter methods are doing is hidden from them.
 Simplicity: It simplifies the maintenance of the application by keeping classes separated and
preventing them from tightly coupling with each other.
 Aesthetics: Bundling data and methods within a class makes code more readable and
maintainable

What is Polymorphism in Python?


Polymorphism in Python is the ability of an object to take many forms. In simple words,
polymorphism allows us to perform the same action in many different ways.

In polymorphism, a method can process objects differently depending on the class type or
data type. Let’s see simple examples to understand it better.

For Example,The built-in function len() calculates the length of an object depending upon its
type. If an object is a string, it returns the count of characters, and If an object is a list, it returns
the count of items in a list. The len() method treats an object as per its class type.

Polymorphism with Inheritance


Polymorphism is mainly used with inheritance. In inheritance, child class inherits the attributes
and methods of a parent class. The existing class is called a base class or parent class, and the
new class is called a subclass or child class or derived class.

Using method overriding polymorphism allows us to defines methods in the child class that
have the same name as the methods in the parent class. This process of re-implementing the
inherited method in the child class is known as Method Overriding.

Advantage of method overriding


 It is effective when we want to extend the functionality by altering the inherited method.
Or the method inherited from the parent class doesn’t fulfill the need of a child class, so
we need to re-implement the same method in the child class in a different way.
 Method overriding is useful when a parent class has multiple child classes, and one of
that child class wants to redefine the method. The other child classes can use the parent
class method. Due to this, we don’t need to modification the parent class code

In polymorphism, Python first checks the object’s class type and executes the appropriate
method when we call the method.

#polymorphism and inheritance


class person:
def __init__(self,name,ID):
self.Name=name
self.Id=ID
def pass_get(self):
print("go to some where in the university")
class Employee(person):
def pass_get(self):
print(f"{self.Name} go to his/her office")
class Student(person):
def pass_get(self):
print(f"{self.Name}go to Dorm/Class room")
P=person("hana",1234)
E=Employee("mm",12)
S=Student("ss",12)

As you can see, due to polymorphism, the Python interpreter recognizes that the pass_get ()
methods are overridden for the Student and Employee object. So, it uses the one defined in the
child class (Student and Employee)

Method Overloading
The process of calling the same method with different parameters is known as method
overloading. Python does not support method overloading. Python considers only the latest
defined method even if you overload the method. Python will raise a TypeError if you overload
the method.

Inheritance in Python
The process of inheriting the properties of the parent class into a child class is called
inheritance. The existing class is called a base class or parent class and the new class is called a
subclass or child class or derived class.
The main purpose of inheritance is the reusability of code because we can use the existing class
to create a new class instead of creating it from scratch.
In inheritance, the child class acquires all the data members, properties, and functions from the
parent class. Also, a child class can also provide its specific implementation to the methods of
the parent class.

Types of Inheritance
In Python, based upon the number of child and parent classes involved, there are five types of
inheritance.
Single Inheritance: In single inheritance, a child class inherits from a single-parent class. Here
is one child class and one parent class.

#Single Inheritance
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Dog(Animal):
def __init__(self):
self.Age=5
D1=Dog()
D1.Name="boby"
D1.color="brown"
D1.display()
print(D1.Age)
Multiple Inheritance: In multiple inheritance, one child class can inherit from multiple parent
classes. So here is one child class and multiple parent classes.

#Multiple Inheritance
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Dog(Animal):
def __init__(self):
self.Age=5
class Cat(Animal):
def __init__(self):
self.s="Meww"
def CSound(self):
print(f'Cat says {self.s}')
D1=Dog()
D1.Name="cute"
D1.color="white"
D1.display()
print(f'Age: {D1.Age}')
C1=Cat()
C1.Name="cute"
C1.color="white"
C1.display()
C1.CSound()

Multilevel inheritance: In multilevel inheritance, a class inherits from a child class or derived
class. Suppose three classes A, B, C. A is the superclass, B is the child class of A, C is the child
class of B. In other words, we can say a chain of classes is called multilevel inheritance.
# Multilevel Inheritance
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Dog(Animal):
def __init__(self):
self.Age=5
class Puppy(Dog):
def __init__(self):
print("I am little dog")
P1=Puppy()
P1.Name="cute"
P1.color="white"
P1.Age=1
P1.display()
print(f'Age: {P1.Age}')

Hierarchical inheritance: In Hierarchical inheritance, more than one child class is derived from
a single parent class. In other words, we can say one parent class and multiple child classes.

# Hierarchical inheritance
class person:
def __init__(self,name,ID):
self.Name=name
self.Id=ID
def Show(self):
print(f"Name:{self.Name}")
print(f"Name:{self.Id}")
class Employee(person):
def pass_get(self):
print(f"{self.Name} go to his/her office")
class Student(person):
def pass_get(self):
print(f"{self.Name}go to Dorm/Class room")
P=person("hana",1234)
E=Employee("mm",12)
S=Student("ss",12)
E.pass_get()
E.Show()
S.pass_get()
S.Show()

Hybrid inheritance: When inheritance is consists of multiple types or a combination of different


inheritance is called hybrid inheritance.

Python super() function


When a class inherits all properties and behavior from the parent class is called inheritance. In
such a case, the inherited class is a subclass and the latter class is the parent class.

In child class, we can refer to parent class by using the super() function. The super function
returns a temporary object of the parent class that allows us to call a parent class method inside a
child class method.
Benefits of using the super() function:
1. We are not required to remember or specify the parent class name to access its methods.
2. We can use the super() function in both single and multiple inheritances.
3. The super() function support code reusability as there is no need to write the entire
function
#super function used inside cat to call display method of Animal
class Animal:
def __init__(self):
self.Name=name
self.color=color
def display(self):
print(f'Name: {self.Name} Color:{self.color}')
class Cat(Animal):
def __init__(self):
self.s="Meww"
def CSound(self):
super().display()
print(f'Cat says {self.s}')
C1=Cat()
C1.Name="cute"
C1.color="white"
C1.CSound()
GUI (Graphical User Interface)
A graphical user interface (GUI) is a desktop interface that allows you to communicate with
computers. They carry out various activities on desktop computers, laptops, and other mobile
devices. Text-Editors and other graphical user interface applications build, read, download, and
erase various types of files.
We can use any of the following toolkits in Python for GUI programming.
Tkinter: is a standard package used for GUI programming in Python. This is built on top of
the Tk interface.
PyQt: is a Python toolkit binding of the Qt toolkit. Qt is a C++ framework that is used by
Python to implement a cross-platform PyQt toolkit as a plug-in.
wxPython: wxPython is also a cross-platform GUI toolkit. It is a wrapper for the API
wxWidgets.

Python Tkinter Module


we will concentrate on the Tkinter module.
Tkinter is a standard Python library used for GUI programming. It provides an object-oriented
interface to build the Tk GUI toolkit. It is a faster and easier way to build a GUI in Python.

Tkinter is the first option for a lot of learners and developers because it is quick and convenient
to use. Tkinter is a Python library that can be used to construct basic graphical user interface
(GUI) applications. In Python, it is the most widely used module for GUI applications.
The creation of a blank GUI interface is the first step of the creation of any GUI. This process of
creating a simple GUI in Tkinter requires the following steps:

1. Tkinter, the first step is to install the Tkinter module in the python shell.

import tkinter or from tkinter import *

2. Creating the main window for the application:


To create the main GUI window using the function Tk() function. The syntax of the Tk()
function is: win=tkinter.Tk()

3. Adding the required widgets to the window:


Tinter provides 19 widgets.

4. Calling the function mainloop():


This is the function that gets triggered when an event occurs. This is an infinite loop that runs till
we close the application window. win.mainloop()
Tkinter widgets
There are various widgets like button, canvas, label, entry, etc. that are used to build the python
GUI applications.
We can also set the size of the window by using the geometry('width X height') and title using
title(string)

To organize our widgets in window we can use one of the following methods:
1. pack(): This method organizes widgets in blocks before positioning the parent widget. It has
side attribute with value top, bottom, left, right and anchor with value n, ne, nw, s, se, sw, e, w,
center
2. grid(): This method organizes widgets in the grid or table form before positioning the parent
widget. It has two attribute which contain integer values row and column
3. place(): This method organizes the widgets by placing them in the position mentioned in the
code. The position is mentioned based on x-y axis

1. Button:
To add a button to the window, we use the Button() method. Its syntax is given below.
btn=Button(win, option=value), win= name of the window and put following option values

activebackground: This parameter sets the background color when the cursor is on the button.
activeforeground: This parameter sets the foreground color when the cursor is on the button
bg: We give the background color of the button to the parameter
command: We give a function to this parameter. This function contains the code to set the
functionality of the button.
font: This parameter sets the font style of the label of the button
image: This parameter sets the background of the button to the image given
width: This sets the width of the button to the given value
height: This sets the height of the button to the given value

#Example 1
import tkinter
con=tkinter.Tk()
def ff():
print("welcome")
#add widget
B=tkinter.Button(con,text="Click",bg="red",command=ff)
B.grid()
con.mainloop()

Canvas:

This lets you draw shapes such as lines, polygons, etc., and other layouts like graphics, text, and
widgets. Its syntax is given below.

can=Canvas(win, option=value)

The parent window is given as the parameter master. In addition, we have parameters like:
a. bd: This parameter sets the border width. The value should be given in pixels
b. bg: We give the background color of the canvas to this parameter
c. cursor: This sets the cursor used when the cursor is on the canvas
d. highlightcolor: This parameter sets the color of the focus highlight
e. width: This sets the width of the canvas to the given value
f. height: This sets the height of the canvas to the given value

#Example 2
import tkinter
con=tkinter.Tk()
con.title("Welcome to tkinter GUI")
con.geometry("150x200")
ca=tkinter.Canvas(con)
p=ca.create_rectangle(100,150,60,80,fill="blue")
ca.grid()
con.mainloop()

CheckButton:

This widget lets the display multiple options for the user to select. The user can select any
number of checkboxes. Its syntax is:

cb=CheckButton(win, option=value)

The parent window is given as the master. There are many other parameters related to the check
button like:
a. activebackground: This parameter sets the background color when the cursor is on the check
button
b. activeforeground: This parameter sets the foreground color when the cursor is on the check
button
c. bg: We give the background color of the check button
d. command: This takes a function that contains the code to set the functionality of the check
button.
e. font: This parameter sets the font style of the label of the button
f. image: This sets the input image on the check button

#Example 3
import tkinter
con=tkinter.Tk()
con.title("Welcome to tkinter GUI")
con.geometry("150x200")
v1=tkinter.IntVar()
v2=tkinter.IntVar()
cb1=tkinter.Checkbutton(con,text="mango",variable=v1,onvalue=1,offvalue=0)
cb2=tkinter.Checkbutton(con,text="Orange",variable=v2,onvalue=1,offvalue=0)
cb1.pack()
cb2.pack()
con.mainloop()
Entry:

This widget allows you to take single-line input from the user. Its syntax is:

ent=Entry(win, option=value)

The parent window is given as the win. Besides, it has many other parameters like:
a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the entry using this parameter
c. cursor: This sets the cursor used when the cursor is on the entry
d. command: This takes a function as an argument that gets called.
e. highlightcolor: This parameter sets the color of the focus highlight
f. width: This sets the width of the entry to the given value
g. height: This sets the height of the entry to the given value

Example of the entry:


from tkinter import *
win=tkinter.Tk() #creating the main window and storing the window object in 'win'
win.geometry('300x100') #setting the size of the window
tkinter.Label(win, text='Name').grid(row=0)
tkinter.Label(win, text='Email').grid(row=1)
ent1 = tkinter.Entry(win)
ent2 = tkinter.Entry(win)
ent1.grid(row=0, column=1)
ent2.grid(row=1, column=1)
win.mainloop()

Frame:

This widget acts as a container of other widgets. This is used to organize and position the
widgets. Its syntax is:

frame=Frame(win, option=value)

The parent window is given as the ‘win’ parameter. There are other parameters like:
a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the frame using this parameter
c. cursor: This sets the cursor used when the cursor is on the frame
d. highlightcolor: This parameter sets the color of the focus highlight
e. width: This sets the width of the frame
f. height: This sets the height of the frame

Example of the frame:

from tkinter import *


win=Tk() #creating the main window and storing the window object in 'win'
win.title('Welcome') #setting title of the window
win.geometry('250x50')
frame = tkinter.Frame(win)
frame.pack()
second_frame = tkinter.Frame(win)
second_frame.pack( side = BOTTOM )
red_button = tkinter.Button(frame, text = 'Hello', bg ='red',fg='white')
red_button.pack( side = LEFT)
green_button = tkinter .Button(frame, text = 'Hi', fg='white',bg='green')
green_button.pack( side = LEFT )
blue_button = tkinter .Button(second_frame, text ='Blue', fg ='white',bg='blue')
blue_button.pack( side = LEFT )
win.mainloop() #running the loop that works as a trigger

Label:

This widget lets us display a text or an image. Its syntax is:

lab=Label(win, option=value)

The parent window is given as the win parameter. There are other parameters like:
a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the label using this parameter
c. command: This takes a function that contains the code to set the functionality of the label.
d. font: This parameter sets the font style of the text in the label
e. image: This parameter sets the image to display
f. width: This sets the width of the label
g. height: This sets the height of the label

Example of the label:

from tkinter import *


win=Tk() #creating the main window and storing the window object in 'win'
win.title('Welcome') #setting title of the window
win.geometry('250x50')
lab= tkinter .Label(win,text='Python GUI',width=50,height=30)
lab.pack()
win.mainloop() #running the loop that works as a trigger

Listbox:

This widget lets us give a list of items to the user to choose from. Its syntax is:

lb=Listbox(win, option=value)

There are parameters like:


a. bd: This parameter sets the border width in pixels
b. bg: We can set the background color of the Listbox using this parameter
c. font: This parameter sets the font style of the text of items in the Listbox
d. highlightcolor: This parameter sets the color of the focus highlight
e. image: This parameter sets the background image of the Listbox
f. width: This sets the width of the listbox
g. height: This sets the height of the Listbox
We can use the insert() function to add elements to the Listbox.

Example of the Listbox:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
win.title('Welcome') #setting title of the window
lb = tkinter.Listbox(win)
lb.insert(1, 'Milk')
lb.insert(2, 'Espress')
lb.insert(3, 'Michato')
lb.insert(4,'Coffee')
lb.insert(5,'Tea')
lb.insert(6, 'Others')
lb.pack()
win.mainloop() #running the loop that works as a trigger

MenuButton:

This lets us add menus to the GUI. We can add a function to the menu button to open the menu
options. Its syntax is:

mb=MenuButton(win, option=value)

A. activebackground: This parameter sets the background color when the cursor is on the menu
button
B. activeforeground: This parameter sets the foreground color when the cursor is on the menu
button
C. bd: This parameter sets the border width in pixels
D. bg: We can set the background color of the menu button using this parameter
E. cursor: This sets the cursor used in the menu button
F. highlightcolor: This parameter sets the color of the focus highlight
G. image: This parameter sets the background image of the menu button
H. width: This sets the width of the menu button
I. height: This sets the height of the menu button
Let us see an example.
Example of the menu button:
from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
win.geometry('200x100')
mb = Menubutton ( win, text = 'Menu')
mb.grid()
mb.menu = Menu ( mb)
mb['menu'] = mb.menu
var1 = IntVar()
var2 = IntVar()
var3 = IntVar()
mb.menu.add_checkbutton ( label ='Home', variable = var1 )
mb.menu.add_checkbutton ( label = 'Profile', variable = var2 )
mb.menu.add_checkbutton ( label = 'Sign Out', variable = var3 )
mb.pack()
win.mainloop() #running the loop that works as a trigger

Menu:

This widget allows us to create all kinds of menus in the application. Its syntax is:

mn=Menu(win, option=value)

The parent window is given as the ‘win’ parameter. In addition, we can set other parameters like:

A. activebackground: This parameter sets the background color when the cursor is on the menu
B. activeforeground: This parameter sets the foreground color when the cursor is on the menu
C. bg: We can set the background color of the menu using this parameter
D. command: This takes a function that contains the code to set the functionality of the menu
E. font: This parameter sets the font style of the text of items in the menu
F. image: This parameter sets the background image of the menu
G. title: This sets the title of the menu

Example of the menu:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
win.geometry('300x150')
mn = Menu(win)
win.config(menu=mn)
file_menu = Menu(mn)
mn.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='New')
file_menu.add_command(label='Open...')
file_menu.add_command(label='Save')
file_menu.add_separator()
file_menu.add_command(label='About')
file_menu.add_separator()
file_menu.add_command(label='Exit', command=win.quit)
help_menu = Menu(mn)
mn.add_cascade(label='Help', menu=help_menu)
help_menu.add_command(label='Feedback')
help_menu.add_command(label='Contact')
win.mainloop() #running the loop that works as a trigger

Message: This widget is similar to a label. Here we can display multiline and non-editable text.
Its syntax is:
msg=Message(master, option=value)

The parent window is given as the ‘master’ parameter. The other parameters that let us set other
features are:
A. bd: This sets the border around the message widget
B. bg: We can set the background color of the message using this parameter
C. font: This parameter sets the font style in the message
D. image: This parameter sets the background image of the message widget
E. width: This sets the width of the message
F. height: This sets the height of the message

Example of the Message


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
message ='Hello! Welcome to PythonGeeks'
msg = tkinter.Message(win, text = message)
msg.config(bg='lightblue',fg='white')
msg.pack( )
win.mainloop() #running the loop that works as a trigger

Radiobutton:

This widget lets us give multiple options to the user and he/she can choose one of the options. Its
syntax is:

rb=Radiobutton(win, option=value)

A. activebackground: This parameter sets the background color when the cursor is on the radio
button
B. activeforeground: This parameter sets the foreground color when the cursor is on the radio
button
C. bg: We can set the background color of the radio button using this parameter
D. command: This takes a function that contains the code to set the functionality of the radio
button.
E. font: This parameter sets the font style if the items in the radio button
F. image: This parameter sets the background image of the radio button widget
G. width: This sets the width of the radio button
H. height: This sets the height of the radio button

Example of the radio button:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
var = tkinter.IntVar()
tkinter.Radiobutton(win, text='Male', variable=var, value=1).pack(anchor=W)
tkinter.Radiobutton(win, text='Female', variable=var, value=2).pack(anchor=W)
tkinter.Radiobutton(win, text='Other', variable=var, value=3).pack(anchor=W)
win.mainloop() #running the loop that works as a trigger

Scale: This provides a slider that allows the user to slide any value. Its syntax is:
sc=Scale(win, option=value)

A. activebackground: This parameter sets the background color when the cursor is on the scale
B. bg: We can set the background color of the scale using this parameter
C. cursor: This sets the cursor used in the scale
D. from_: This sets the value of one end of the scale
E. image: This parameter sets the background image of the scale
F. orient: Set the orientation of the widget to either HORIZONTAL or VERTICAL. By default,
it is vertical.
G. to: It sets the value of the other end of the scale.
H. width: This sets the width of the scale

Example of the scale:

import tkinter
win=tkinter.Tk() #creating the main window and storing the window object in 'win'
sc1= tkinter.Scale(win, from_=0, to=15)
sc1.pack()
sc2 = tkinter.Scale(win, from_=10, to=100, orient='horizontal')
sc2.pack()
win.mainloop() #running the loop that works as a trigger

Scrollbar:

This widget gives the scrolling feature to the other widgets like lists. Its syntax is:

sb=Scrollbar(win, option=value)

A. activebackground: This parameter sets the background color when the cursor is on the
scrollbar
B. bd: This parameter sets the border around the scrollbar
C. bg: We can set the background color of the scrollbar
D. cursor: This sets the cursor used when the cursor is on the scrollbar
E. width: This sets the width of the scrollbar

Example of the scrollbar:


import tkinter
win=tkinter.Tk() #creating the main window and storing the window object in 'win'
sb = tkinter.Scrollbar(win)
sb.pack( side = 'right', fill ='y' )
list_1 = tkinter.Listbox(win, yscrollcommand = sb.set )
for i in range(100):
list_1.insert('end', 'Item ' + str(i))
list_1.pack( side = 'left', fill = 'both' )
sb.config( command = list_1.yview )
win.mainloop()

Text: This is a widget that can be used to display multiline text. Its syntax is:

txt=Text(win, option=value)

The parent window is given as the ‘win’ parameter. The other parameters are:

A. insertbackground: This parameter sets the background color of text


B. bg: We can set the background color of the test
C. font: This sets the font style of the text in this widget
D. highlightcolor: This sets the highlight color when the cursor is on this widget
E. height: This sets the height of the widget
F. image: This sets the image on the text widget
G. width: This sets the width of the text

Example of the text:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
txt= Text(win, height=5, width=45)
txt.pack()
txt.insert(INSERT,"Hello!")
txt.insert(END, 'PythonGeeks\nOne stop for building your Python skills\n')
win.mainloop() #running the loop that works as a trigger

TopLevel:

This widget provides a separate container window. This does not need a parent window. Its
syntax is:

tl=TopLevel(win, option=value)

The parent window is given as the ‘win’ parameter. The other parameters that let us set other
features are:

A. bd: This parameter sets the border around the top level
B. bg: We can set the background color of the top level
C. cursor: This sets the cursor used when the cursor is on the top level
D. height: This sets the height of the widget
E. width: This sets the width of the top level

Example of the top level:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
win.title('PythonGeeks')
tl= Toplevel()
tl.title('Greetings')
win.mainloop() #running the loop that works as a trigger

SpinBox:

This is similar to the entry widget. Here, instead of entering random input, the user is bound to
enter any of the fixed numbers. Its syntax is:

sb=SpinBox(win, option=value)

The parent window is given as the ‘win’ parameter. The other parameters that let us set other
features are:
A. activebackground: This parameter sets the background color when the cursor is on the
SpinBox
B. bd: This parameter sets the border around the SpinBox
C. bg: We can set the background color of the SpinBox
D. command: This takes a function that contains the code to set the functionality of the SpinBox
E. cursor: This sets the cursor used when the cursor is on the SpinBox
F. from_: This sets the value of one end of the SpinBox
G. to: It sets the value of the other end of the SpinBox.
H. width: This sets the width of the SpinBox

Example of the SpinBox:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
sb = Spinbox(win, from_ = 1, to = 15)
sb.pack()
win.mainloop() #running the loop that works as a trigger

PannedWindow:

This is a widget that acts as a container of multiple panes oriented horizontally or vertically. Its
syntax is:

pw=PannedWindow(win, option=value)

A. bd: This parameter sets the border around the PannedWindow


B. bg: We can set the background color of the PannedWindow
C. cursor: This sets the cursor used when the cursor is on the PannedWindow
D. width: This sets the width of the PannedWindow

Example of the PannedWindow:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
pw = PanedWindow()
pw.pack(fill = BOTH, expand = 1)
w1 = Scrollbar(win)
w1.pack( side = RIGHT, fill = Y )
list_1 = Listbox(win, yscrollcommand = w1.set )
for i in range(50):
list_1.insert(END, 'ListItem ' + str(i))
list_1.pack( side = LEFT, fill = BOTH )
w1.config( command = list_1.yview )
pw.add(w1)
w2 = PanedWindow(pw, orient = VERTICAL)
pw.add(w2)
sc = Scale( w2, orient = HORIZONTAL)
w2.add(sc)
w3=Button(w2,text="Done")
w2.add(w3)
win.mainloop() #running the loop that works as a trigger
LabelFrame: This widget acts as a container for complex window layouts. Its syntax is:

lf=LabelFrame(win, option=value)

A. bd: This parameter sets the border around the LabelFrame


B. bg: We can set the background color of the LabelFrame
C. cursor: This sets the cursor used when the cursor is on the LabelFrame
D. font: This sets the font style of the text in this widget
E. highlightbackground: This sets the highlight color when the widget is not in focus
F. highlightcolor: This sets the highlight color when the cursor is on this widget
G. height: This sets the height of the widget
H. labelAnchor: This is sed to specify where to place the label
I. text: This specifies the text to be displayed in the widget
J. width: This sets the width of the LabelFrame

Example of the LabelFrame:


from tkinter import *
win=Tk() #creating the main window and storing the window object in 'win'
lf=LabelFrame(win,text="Message")
lf.pack(fill="both",expand="yes")
lb=Label(lf,text="Seccesfully made a LableFrame")
lb.pack()
win.mainloop()

tkMessageBox:
This widget is used to show pop-up messages. Remember we used this widget while discussing
the button widget! The syntax of this widget is:

mb=tkMessageBox.FunctionName(title, message [, options])

In this, the function name can be any of the following functions:


A. askquestion()
B. askokcancel()
C. askyesno ()
D. askretrycancel ()
E. showerror ()
F. showinfo()
G. showwarning()

Example of messagebox:
from tkinter import *
from tkinter import messagebox
win=Tk() #creating the main window and storing the window object in 'win'
win.geometry("200x100")
def greet():
messagebox.showinfo("Greetings", "Hello Pythoneer!")
btn = Button(win, text = "Click Me", command = greet)
btn.pack()
win.mainloop()

You might also like