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

Python Notes - 5 Unit

The document discusses the importance of data visualization and introduces Matplotlib, a Python library for creating various types of plots and charts. It outlines the benefits of data visualization, including improved decision-making and the ability to identify trends, and details the features, advantages, and disadvantages of using Matplotlib. Additionally, it explains the structure of Matplotlib figures, types of plots available, and provides examples of basic plotting using the library.

Uploaded by

akhilverma9580
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 views104 pages

Python Notes - 5 Unit

The document discusses the importance of data visualization and introduces Matplotlib, a Python library for creating various types of plots and charts. It outlines the benefits of data visualization, including improved decision-making and the ability to identify trends, and details the features, advantages, and disadvantages of using Matplotlib. Additionally, it explains the structure of Matplotlib figures, types of plots available, and provides examples of basic plotting using the library.

Uploaded by

akhilverma9580
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Python (Unit 5)

 Python Packages

Human minds are more adaptive for the visual representation of data rather than textual data. We can
easily understand things when they are visualized. It is better to represent the data through the graph where
we can analyse the data more efficiently and make the specific decision according to data analysis. Before
learning the matplotlib, we need to understand data visualization and why data visualization is important.

 Data Visualization

 Graphics provides an excellent approach for exploring the data, which is essential for presenting
results. Data visualization is a new term. It expresses the idea that involves more than just
representing data in the graphical form (instead of using textual form).
 This can be very helpful when discovering and getting to know a dataset and can help with
classifying patterns, corrupt data, outliers, and much more.
 With a little domain knowledge, data visualizations can be used to express and demonstrate key
relationships in plots and charts.

There are five key plots that are used for data visualization.

 There are five phases which are essential to make the decision for the organization.

 Visualize: We analyse the raw data, which means it makes complex data more accessible,
understandable, and more usable. Tabular data representation is used where the user will look up
a specific measurement, while the chart of several types is used to show patterns or relationships
in the data for one or more variables.
 Analysis: Data analysis is defined as cleaning, inspecting, transforming, and modelling data to
derive useful information. Whenever we make a decision for the business or in daily life, is by
past experience. What will happen to choose a particular decision, it is nothing but analysing
Dr. Yusuf Perwej
our past. That may be affected in the future, so the proper analysis is necessary for better decisions
for any business or organization.
 Document Insight: Document insight is the process where the useful data or information is
organized in the document in the standard format.
 Transform Data Set: Standard data is used to make the decision more effectively.

 Why need data visualization?

Data visualization can perform below tasks:


 It identifies areas that need improvement and attention.
 It clarifies the factors.
 It helps to understand which product to place where.
 Predict sales volumes.

 Benefit of Data Visualization

Here are some benefits of the data visualization, which helps to make an effective decision for the
organizations or business:
1. Building ways of absorbing information
Data visualization allows users to receive vast amounts of information regarding operational and business
conditions. It helps decision-makers to see the relationship between multi-dimensional data sets. It offers
new ways to analyses data through the use of maps, fever charts, and other rich graphical representations.
Visual data discovery is more likely to find the information that the organization needs and then end up
with being more productive than other competitive companies.
2. Visualize relationship and patterns in Businesses
The crucial advantage of data visualization is that it is essential to find the correlation between operating
conditions and business performance in today's highly competitive business environment.
3. Take action on the emerging trends faster
Data visualization allows the decision-maker to grasp shifts in customer behaviour and market conditions
across multiple data sets more efficiently. Having an idea about the customer's sentiments and other data
discloses an emerging opportunity for the company to act on new business opportunities ahead of their
competitor.
4. Geological based Visualization
Geo-spatial visualization is occurred due to many websites providing web-services, attracting visitor's
interest. These types of websites are required to take benefit of location-specific information, which is
already present in the customer details.

 Matplotlib

Matplotlib is an open-source drawing library that supports various drawing types. You can generate plots,
histograms, bar charts, and other types of charts with just a few lines of code. It’s often used in web
application servers, shells, and Python scripts. Matplotlib is a Python library which is defined as a multi-
platform data visualization library built on Numpy array. Developers can also use matplotlib’s APIs
(Application Programming Interfaces) to embed plots in GUI applications. A Python matplotlib script is

Dr. Yusuf Perwej


structured so that a few lines of code are all that is required in most instances to generate a visual data
plot.

The John D. Hunter originally conceived the matplotlib in 2002. It has an active development
community and is distributed under a BSD-style license. Its first version was released in 2003, and the
latest version 3.1.1 is released on 1 July 2019.

Matplotlib 2.0.x supports Python versions 2.7 to 3.6 till 23 June 2007. Python3 support started with
Matplotlib 1.2. Matplotlib 1.4 is the last version that supports Python 2.6.

There are various toolkits available that are used to enhance the functionality of the matplotlib. Some of
these tools are downloaded separately, others can be shifted with the matplotlib source code but have
external dependencies.

 Bashmap: It is a map plotting toolkit with several map projections, coastlines, and political
boundaries.
 Cartopy: It is a mapping library consisting of object-oriented map projection definitions, and
arbitrary point, line, polygon, and image transformation abilities.
 Excel tools: Matplotlib provides the facility to utilities for exchanging data with Microsoft Excel.
 Mplot3d: It is used for 3D plots.
 Natgrid: It is an interface to the Natgrid library for irregular gridding of the spaced data.

 Why and when should choose Matplotlib for Data Visualization

Matplotlib is popular due to its ease of use, extensive documentation, and wide range of plotting
capabilities. It offers flexibility in customization, supports various plot types, and integrates well with
other Python libraries like NumPy and Pandas.

Matplotlib is a suitable choice for various data visualization tasks, including exploratory data analysis,
scientific plotting, and creating publication-quality plots. It excels in scenarios where users require
fine-grained control over plot customization and need to create complex or specialized visualizations.

 Advantages of Matplotlib

 Versatility: Matplotlib can create a wide range of plots, including line plots, scatter plots, bar plots,
histograms, pie charts, and more.
 Customization: It offers extensive customization options to control every aspect of the plot, such as
line styles, colors, markers, labels, and annotations.
 Integration with NumPy: Matplotlib integrates seamlessly with NumPy, making it easy to plot data
arrays directly.
 Publication Quality: Matplotlib produces high-quality plots suitable for publication with fine-grained
control over the plot aesthetics.
 Wide Adoption: Due to its maturity and flexibility, Matplotlib is widely adopted in the scientific and
engineering communities.
 Extensible: Matplotlib is highly extensible, with a large ecosystem of add-on toolkits and extensions
like Seaborn, Pandas plotting functions, and Basemap for geographical plotting.
 Cross-Platform: It is platform-independent and can run on various operating systems, including
Windows, macOS, and Linux.
 Interactive Plots: Matplotlib supports interactive plotting through the use of widgets and event
handling, enabling users to explore data dynamically.

Dr. Yusuf Perwej


 Integration with Jupyter Notebooks: Matplotlib works seamlessly with Jupyter Notebooks, allowing
for interactive plotting and inline display of plots.
 Rich Documentation and Community Support: Matplotlib has comprehensive documentation and
a large community of users and developers, making it easy to find help, tutorials, and examples.

 Disadvantages of Matplotlib

 Steep Learning Curve: For beginners, Matplotlib can have a steep learning curve due to its
extensive customization options and sometimes complex syntax.
 Verbose Syntax: Matplotlib’s syntax can be verbose and less intuitive compared to other plotting
libraries like Seaborn or Plotly, making it more time-consuming to create and customize plots.
 Default Aesthetics: The default plot aesthetics in Matplotlib are often considered less visually
appealing compared to other libraries, requiring more effort to make plots visually attractive.
 Limited Interactivity: While Matplotlib does support interactive plotting to some extent, it does not
offer as many interactive features and options as other libraries like Plotly.
 Limited 3D Plotting Capabilities: Matplotlib’s 3D plotting capabilities are not as advanced and
user-friendly as some other specialized 3D plotting libraries.
 Performance Issues with Large Datasets: Matplotlib can sometimes be slower and less efficient
when plotting large datasets, especially compared to more optimized plotting libraries.
 Documentation and Error Messages: Although Matplotlib has comprehensive documentation,
some users find it challenging to navigate, and error messages can sometimes be cryptic and hard to
debug.
 Dependency on External Libraries: Matplotlib relies on other libraries like NumPy and SciPy for
many of its functionalities, which can sometimes lead to compatibility issues and dependency
management issues.
 Limited Native Support for Statistical Plotting: While Matplotlib can create basic statistical plots,
it lacks some advanced statistical plotting capabilities that are available in specialized libraries like
Seaborn.
 Less Modern Features: Matplotlib has been around for a long time, and some users find that it lacks
some of the modern plotting features and interactive visualization capabilities found in newer
libraries.

Despite these disadvantages, Matplotlib remains a popular choice for data visualization in Python due
to its flexibility, versatility, and extensive capabilities. Many of its limitations can be overcome with
practice, and it can be effectively used for creating high-quality plots with the right knowledge and
skills.

Matplotlib is a versatile and powerful library for creating high-quality plots and visualizations in
Python. With its extensive customization options and wide range of plotting capabilities, it is widely
used in the scientific, engineering, and data science communities for data exploration, analysis, and
presentation.

 Matplotlib Figure

In Matplotlib, a figure is the top-level container that holds all the elements of a plot. It represents the
entire window or page where the plot is drawn.

Dr. Yusuf Perwej


The parts of a Matplotlib figure include (as shown in the figure above).

 Figures in Matplotlib: The Figure object is the top-level container for all elements of the plot. It
serves as the canvas on which the plot is drawn. You can think of it as the blank sheet of paper on
which you’ll create your visualization.
 Axes in Matplotlib: Axes are the rectangular areas within the figure where data is plotted. Each figure
can contain one or more axes, arranged in rows and columns if necessary. Axes provide the coordinate
system and are where most of the plotting occurs.
 Axis in Matplotlib: Axis objects represent the x-axis and y-axis of the plot. They define the data
limits, tick locations, tick labels, and axis labels. Each axis has a scale and a locator that determine
how the tick marks are spaced.
 Marker in Matplotlib: Markers are symbols used to denote individual data points on a plot. They can
be shapes such as circles, squares, triangles, or custom symbols. Markers are often used in scatter plots
to visually distinguish between different data points.
 Adding lines to Figures: Lines connect data points on a plot and are commonly used in line plots,
scatter plots with connected points, and other types of plots. They represent the relationship or trend
between data points and can be styled with different colors, widths, and styles to convey additional
information.
 Matplotlib Title: The title is a text element that provides a descriptive title for the plot. It typically
appears at the top of the figure and provides context or information about the data being visualized.
 Axis Labels in Matplotlib: Labels are text elements that provide descriptions for the x-axis and y-
axis. They help identify the data being plotted and provide units or other relevant information.
 Ticks: Tick marks are small marks along the axis that indicate specific data points or intervals. They
help users interpret the scale of the plot and locate specific data values.
 Tick Labels: Tick labels are text elements that provide labels for the tick marks. They usually display
the data values corresponding to each tick mark and can be customized to show specific formatting or
units.
 Matplotlib Legend: Legends provide a key to the symbols or colors used in the plot to represent
different data series or categories. They help users interpret the plot and understand the meaning of
each element.
 Matplotlib Grid Lines: Grid lines are horizontal and vertical lines that extend across the plot,
corresponding to specific data intervals or divisions. They provide a visual guide to the data and help
users identify patterns or trends.
 Spines of Matplotlib Figures: Spines are the lines that form the borders of the plot area. They separate
the plot from the surrounding whitespace and can be customized to change the appearance of the plot
borders.

Dr. Yusuf Perwej


 Different Types of Plots in Matplotlib

Matplotlib offers a wide range of plot types to suit various data visualization needs. Here are some of
the most commonly used types of plots in Matplotlib:
 Line Graph
 Stem Plot
 Bar chart
 Histograms
 Scatter Plot
 Stack Plot
 Box Plot
 Pie Chart
 Error Plot
 Violin Plot
 3D Plots

 Matplotlib Architecture

There are three different layers in the architecture of the matplotlib which are the following:

 Backend Layer
 Artist layer
 Scripting laye

 Backend layer : The backend layer is the bottom layer of the figure, which consists of the
implementation of the various functions that are necessary for plotting. There are three essential
classes from the backend layer FigureCanvas(The surface on which the figure will be drawn),
Renderer(The class that takes care of the drawing on the surface), and Event(It handle the mouse
and keyboard events).
 Artist Layer : The artist layer is the second layer in the architecture. It is responsible for the various
plotting functions, like axis, which coordinates on how to use the renderer on the figure canvas.
 Scripting layer : The scripting layer is the topmost layer on which most of our code will run. The
methods in the scripting layer, almost automatically take care of the other layers, and all we need to
care about is the current state (figure & subplot).

 Basic Example of plotting Graph

Here is the basic example of generating a simple graph.


Example:
from matplotlib import pyplot as plt
#ploting our canvas
plt.plot([1,2,3],[4,5,1])
#display the graph
plt.show()

Output:

Dr. Yusuf Perwej


It takes only three lines to plot a simple graph using the Python matplotlib. We can add titles, labels to
our chart which are created by Python matplotlib library to make it more meaningful. The example is
the following:

Example:
from matplotlib import pyplot as plt

x = [5, 2, 7]
y = [1, 10, 4]
plt.plot(x, y)
plt.title('Line graph')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

Output:

The graph is more understandable from the previous graph.

 Working with Pyplot

The matplotlib.pyplot is the collection command style functions that make matplotlib feel like
working with MATLAB. The pyplot functions are used to make some changes to figure such as create
a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot
including labels, etc.

It is good to use when we want to plot something quickly without instantiating any figure or Axes.

While working with matplotlib.pyplot, some states are stored across function calls so that it keeps
track of the things like current figure and plotting area, and these plotting functions are directed to the
current axes. The pyplot module provide the plot() function which is frequently use to plot a graph.

Example:
from matplotlib import pyplot as plt
plt.plot([1,2,3,4,5])
plt.ylabel("y axis")

Dr. Yusuf Perwej


plt.xlabel('x axis')
plt.show()

Output:

In the above program, it plots the graph x-axis ranges from 0-4 and the y-axis from 1-5. If we provide a
single list to the plot(), matplotlib assumes it is a sequence of y values, and automatically generates the
x values. Since we know that python index starts at 0, the default x vector has the same length as y but
starts at 0. Hence the x data are [0, 1, 2, 3, 4].

We can pass the arbitrary number of arguments to the plot(). For example, to plot x versus y, we can do
this following way:

Example:
from matplotlib import pyplot as plt
plt.plot([1,2,3,4,5],[1,4,9,16,25])
plt.ylabel("y axis")
plt.xlabel('x axis')
plt.show()

Output:

 Formatting the style of the plot

There is an optional third argument, which is a format string that indicates the color and line type of the
plot. The default format string is 'b-'which is the solid blue as you can observe in the above plotted
graph. Let's consider the following example where we plot the graph with the red circle.

Example:
from matplotlib import pyplot as plt
plt.plot([1, 2, 3, 4,5], [1, 4, 9, 16,25], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

Output:

Dr. Yusuf Perwej


 Example format String

'b' Using for the blue marker with default shape.


'ro' Red circle
'-g' Green solid line
'--' A dashed line with the default color
'^k:' Black triangle up markers connected by a dotted line

The matplotlib supports the following color abbreviation:

Character Color
'b' Blue
'g' Green
'r' Red
'c' Cyan
'm' Magenta
'y' Yellow
'k' Black
'w' White

 Plotting with categorical variables

Matplotlib allows us to pass categorical variables directly to many plotting functions:

Example:
from matplotlib import pyplot
names = ['Abhishek', 'Himanshu', 'Devansh']
marks= [87,50,98]

plt.figure(figsize=(9,3))

plt.subplot(131)
plt.bar(names, marks)
plt.subplot(132)
plt.scatter(names, marks)
plt.subplot(133)
plt.plot(names, marks)
plt.suptitle('Categorical Plotting')
plt.show()

Dr. Yusuf Perwej


Output:

In the above program, we have plotted the categorical graph using the subplot() function.
.
 What is subplot()

The Matplotlib subplot() function is defined as to plot two or more plots in one figure. We can use this
method to separate two graphs which plotted in the same axis Matplotlib supports all kinds of subplots,
including 2x1 vertical, 2x1 horizontal, or a 2x2 grid.

It accepts the three arguments: they are nrows, ncols, and index. It denote the number of rows, number
of columns and the index. The subplot() function can be called in the following way.

 subplot(nrows,ncols,index,**kwargs)
 subplot(pos,**kwargs)
 subplot(ax)

Parameters:

 *args:

Three separate integers or three-digit integer describes the position of the subplot. If the three integers
are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows row
and ncol column.

The argument pos are a three-digit integer, where the first digit is denoted the number of rows, the
second digit denoted the number of columns, and the third represents the index of the subplot. For
example, subplot (1, 3, 2) is the same as the subplot (132).

Note: Passed integer must be less than 10.

 **kwargs

The subplot() function also accepts the keyword arguments for the returned axes base class.
Consider the following example:

 Creating different types of graphs

1. Line graph
The line graph is one of charts which shows information as a series of the line. The graph is plotted by
the plot() function. The line graph is simple to plot.

Example:
from matplotlib import pyplot as plt

Dr. Yusuf Perwej


x = [4,8,9]
y = [10,12,15]

plt.plot(x,y)

plt.title("Line graph")
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()

Output:

 We can customize the graph by importing the style module. The style module will be built into
a matplotlib installation. It contains the various functions to make the plot more attractive. In
the below program, we are using the style module.

Example:
from matplotlib import pyplot as plt
from matplotlib import style

style.use('ggplot')
x = [16, 8, 10]
y = [8, 16, 6]
x2 = [8, 15, 11]
y2 = [6, 15, 7]
plt.plot(x, y, 'r', label='line one', linewidth=5)
plt.plot(x2, y2, 'm', label='line two', linewidth=5)
plt.title('Epic Info')
fig = plt.figure()
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.legend()
plt.grid(True, color='k')
plt.show()

Output:

Dr. Yusuf Perwej


 In Matplotlib, the figure (an instance of class plt.Figure) can be supposed of as a single container that
consists of all the objects denoting axes, graphics, text, and labels.

Example:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes()

x = np.linspace(0, 10, 1000)


ax.plot(x, np.sin(x))

Output:

 The matplotlib provides the fill_between() function which is used to fill area around the lines based
on the user defined logic.

Example:
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes()

x = np.linspace(0, 10, 1000)


ax.plot(x, np.sin(x))

import matplotlib.pyplot as plt


import numpy as np

x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 1.2 * np.sin(4 * np.pi * x)
fig, ax = plt.subplots(1, sharex=True)
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=y2 >= y1, facecolor='blue', interpolate=True)
ax.fill_between(x, y1, y2, where=y2 <= y1, facecolor='red', interpolate=True)
ax.set_title('fill between where')

Output:

Dr. Yusuf Perwej


2. Bar graphs

Bar graphs are one of the most common types of graphs and are used to show data associated with the
categorical variables. Matplotlib provides a bar() to make bar graphs which accepts arguments such as:
categorical variables, their value and color.

Example:
from matplotlib import pyplot as plt
players = ['Virat','Rohit','Shikhar','Hardik']
runs = [51,87,45,67]
plt.bar(players,runs,color = 'green')
plt.title('Score Card')
plt.xlabel('Players')
plt.ylabel('Runs')
plt.show()

Output:

 Another function barh() is used to make horizontal bar graphs. It accepts xerr or yerr as
arguments (in case of vertical graphs) to depict the variance in our data.

Example:
from matplotlib import pyplot as plt
players = ['Virat','Rohit','Shikhar','Hardik']
runs = [51,87,45,67]
plt.barh(players,runs, color = 'green')
plt.title('Score Card')
plt.xlabel('Players')
plt.ylabel('Runs')
plt.show()

Output:

Dr. Yusuf Perwej


Other example using the style() function.

Example:
from matplotlib import pyplot as plt
from matplotlib import style

style.use('ggplot')

x = [5,8,10]
y = [12,16,6]

x2 = [6,9,11]
y2 = [7,15,7]

plt.bar(x, y, color = 'y', align='center')


plt.bar(x2, y2, color='c', align='center')

plt.title('Information')

plt.ylabel('Y axis')
plt.xlabel('X axis')

Output:

 Similarly to vertical stack, the bar graph together by using the bottom argument and define the
bar graph, which we want to stack below and its value.

Example:
from matplotlib import pyplot as plt
import numpy as np

countries = ['USA', 'India', 'China', 'Russia', 'Germany']

Dr. Yusuf Perwej


bronzes = np.array([38, 17, 26, 19, 15])
silvers = np.array([37, 23, 18, 18, 10])
golds = np.array([46, 27, 26, 19, 17])
ind = [x for x, _ in enumerate(countries)]

plt.bar(ind, golds, width=0.5, label='golds', color='gold', bottom=silvers+bronzes)


plt.bar(ind, silvers, width=0.5, label='silvers', color='silver', bottom=bronzes)
plt.bar(ind, bronzes, width=0.5, label='bronzes', color='#CD853F')

plt.xticks(ind, countries)
plt.ylabel("Medals")
plt.xlabel("Countries")
plt.legend(loc="upper right")
plt.title("2019 Olympics Top Scorers")

Output:

3. Pie Chart

A pie chart is a circular graph that is broken down in the segment or slices of pie. It is generally used to
represent the percentage or proportional data where each slice of pie represents a particular category.

Example:
from matplotlib import pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
Players = 'Rohit', 'Virat', 'Shikhar', 'Yuvraj'
Runs = [45, 30, 15, 10]
explode = (0.1, 0, 0, 0) # it "explode" the 1st slice

fig1, ax1 = plt.subplots()


ax1.pie(Runs, explode=explode, labels=Players, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

Output:

Dr. Yusuf Perwej


4. Histogram

First, we need to understand the difference between the bar graph and histogram. A histogram is used
for the distribution, whereas a bar chart is used to compare different entities. A histogram is a type of
bar plot that shows the frequency of a number of values compared to a set of values ranges.

For example we take the data of the different age group of the people and plot a histogram with
respect to the bin. Now, bin represents the range of values that are divided into series of intervals. Bins
are generally created of the same size.

Example:
from matplotlib import pyplot as plt
from matplotlib import pyplot as plt
population_age = [21,53,60,49,25,27,30,42,40,1,2,102,95,8,15,105,70,65,55,70,75,60,52,44,43,42,
45]
bins = [0,10,20,30,40,50,60,70,80,90,100]
plt.hist(population_age, bins, histtype='bar', rwidth=0.8)
plt.xlabel('age groups')
plt.ylabel('Number of people')
plt.title('Histogram')
plt.show()

Output:

Another example of plotting histogram.

Example:
from matplotlib import pyplot as plt
# Importing Numpy Library
import numpy as np
plt.style.use('fivethirtyeight')

mu = 50
sigma = 7
Dr. Yusuf Perwej
x = np.random.normal(mu, sigma, size=200)
fig, ax = plt.subplots()

ax.hist(x, 20)
ax.set_title('Historgram')
ax.set_xlabel('bin range')
ax.set_ylabel('frequency')

fig.tight_layout()
plt.show()

Output:

5. Scatter plot

The scatter plots are mostly used for comparing variables when we need to define how much one
variable is affected by another variable. The data is displayed as a collection of points. Each point has
the value of one variable, which defines the position on the horizontal axes, and the value of other
variable represents the position on the vertical axis.

Example:
from matplotlib import pyplot as plt
from matplotlib import style
style.use('ggplot')

x = [5,7,10]
y = [18,10,6]

x2 = [6,9,11]
y2 = [7,14,17]

plt.scatter(x, y)
plt.scatter(x2, y2, color='g')

plt.title('Epic Info')
plt.ylabel('Y axis')
plt.xlabel('X axis')

plt.show()

Output:

Dr. Yusuf Perwej


Example:
import matplotlib.pyplot as plt
x = [2, 2.5, 3, 3.5, 4.5, 4.7, 5.0]
y = [7.5, 8, 8.5, 9, 9.5, 10, 10.5]

x1 = [9, 8.5, 9, 9.5, 10, 10.5, 12]


y1 = [3, 3.5, 4.7, 4, 4.5, 5, 5.2]
plt.scatter(x, y, label='high income low saving', color='g')
plt.scatter(x1, y1, label='low income high savings', color='r')
plt.xlabel('saving*100')
plt.ylabel('income*1000')
plt.title('Scatter Plot')
plt.legend()
plt.show()

Output:

6. 3D graph plot

Matplotlib was initially developed with only two-dimension plot. Its 1.0 release was built with some of
three-dimensional plotting utilities on top of two-dimension display, and the result is a convenient set
of tools for 3D data visualization.

Three-dimension plots can be created by importing the mplot3d toolkit, include with the main
Matplotlib installation.

 from mpl_toolkits import mplot3d

When this module is imported in the program, three-dimension axes can be created by passing the
keyword projection='3d' to any of the normal axes creation routines.

Example:
from mpltoolkits import mplot3d

Dr. Yusuf Perwej


import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')_

Output:

Example:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

height = np.array([100,110,87,85,65,80,96,75,42,59,54,63,95,71,86])
weight = np.array([105,123,84,85,78,95,69,42,87,91,63,83,75,41,80])

scatter(height,weight)

fig = plt.figure()
ax = plt.axes(projection='3d')
# This is used to plot 3D scatter
ax.scatter3D(height,weight)
plt.title("3D Scatter Plot")
plt.xlabel("Height")
plt.ylabel("Weight")
plt.title("3D Scatter Plot")
plt.xlabel("Height")
plt.ylabel("Weight")

plt.show()

Output:

Note: We can use the plot3D () to plot simple 3D line graph.

Example:
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

Dr. Yusuf Perwej


import matplotlib.pyplot as plt

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure()
ax = fig.gca(projection='3d')
theta1 = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta1)
y = r * np.cos(theta1)
ax.plot3D(x, y, z, label='parametric curve', color = 'red')
ax.legend()

plt.show()

Output:

 Important functions of Matplotlib

Functions Description
It is used to plot a simple line graph with x-axis value
plot(x-axis value, y-axis-values) against the y-axis values. show() It is used to display
the graph.
It is used to set the title of the plotted graph as
title("string")
specified by the string.
It is used to set the label for the x-axis as specified by
xlabel("string")
the string.
It is used to set the label for y-axis as specified by the
ylabel("string")
string.
figure() It is used to control a figure level attributes.
subplots(nrows,ncol,index) It is used to add a subplot to recent figure.
It adds a common title to the plotted graph specified by
subtitle("string")
the string.
It provides the simple way to create subplot, in a single
subplots(nrows,ncols,figsize)
call and returns a tuple of a figure and number of axes.
It is an axes level method which is used to set the title
set_title("string")
of the subplots.

Dr. Yusuf Perwej


bar(categorical variables, values,
It is used to create a vertical bar graph.
color)
barh(categorical variables,
It is used to create horizontal bar graphs.
values, color)
legend(loc) It is used to make a legend of the graph.
xtricks(index, categorical It is used to set or get the current tick locations labels
variables) of the x-axis.
pie(value, categorical variables) It is used to create a pie chart.
hist(value, number of bins) It is used to create a histogram.
xlim(start value, end value) It is used to set the limit of values of the x-axis.
ylim(start value, end value) It is used to set the limit of values of the y-axis.
scatter(x-axis values, y-axis It is used to plots a scatter plot with x-axis value
values) against the y-axis values.
axes() It is used to add axes to the recent figure.
It is an axes level method which is used to set the x-
set_xlabel("string")
label of the plot specified as a string.
It is used to set the y-label of the plot specified as a
set_ylabel("string")
string.
scatter3D(x-axis values, y-axis It is used to plot a three-dimension scatter plot with x-
values) axis value against the y-axis.
It is used to plots a three-dimension line graph with x-
plot3D(x-axis values, y-axis
axis values against y-axis values.
values)
 Managing Figure and Axes
Add an Axes to the current figure and make it the current Axes.
axes
cla Clear the current Axes.
clf Clear the current figure.
close Close a figure window.
delaxes Remove an Axes (defaulting to the current Axes) from its figure.
fignum_exists Return whether the figure with the given id exists.
figure Create a new figure, or activate an existing figure.
gca Get the current Axes.
gcf Get the current figure.
get_figlabels Return a list of existing figure labels.
get_fignums Return a list of existing figure numbers.
sca Set the current Axes to ax and the current Figure to the parent of ax.
subplot Add an Axes to the current figure or retrieve an existing Axes.
subplot2grid Create a subplot at a specific location inside a regular grid.
subplot_mosaic Build a layout of Axes based on ASCII art or nested lists.
subplots Create a figure and a set of subplots.
twinx Make and return a second Axes that shares the x-axis.
twiny Make and return a second Axes that shares the y-axis.

Dr. Yusuf Perwej


 Adding data to the plot

Basic
plot Plot y versus x as lines and/or markers.
errorbar Plot y versus x as lines and/or markers with attached errorbars.
scatter A scatter plot of y vs.
plot_date [Deprecated] Plot coercing the axis to treat floats as dates.
step Make a step plot.
loglog Make a plot with log scaling on both the x- and y-axis.
semilogx Make a plot with log scaling on the x-axis.
semilogy Make a plot with log scaling on the y-axis.
fill_between Fill the area between two horizontal curves.
fill_betweenx Fill the area between two vertical curves.
bar Make a bar plot.
barh Make a horizontal bar plot.
bar_label Label a bar plot.
stem Create a stem plot.
eventplot Plot identical parallel lines at the given positions.
pie Plot a pie chart.
stackplot Draw a stacked area plot or a streamgraph.
broken_barh Plot a horizontal sequence of rectangles.
vlines Plot vertical lines at each x from ymin to ymax.
hlines Plot horizontal lines at each y from xmin to xmax.
fill Plot filled polygons.
polar Make a polar plot.

Spans
axhline Add a horizontal line across the Axes.
axhspan Add a horizontal span (rectangle) across the Axes.
axvline Add a vertical line across the Axes.
axvspan Add a vertical span (rectangle) across the Axes.
axline Add an infinitely long straight line.

Spectral
acorr Plot the autocorrelation of x.
angle_spectrum Plot the angle spectrum.
cohere Plot the coherence between x and y.
csd Plot the cross-spectral density.
magnitude_spectrum Plot the magnitude spectrum.
phase_spectrum Plot the phase spectrum.
psd Plot the power spectral density.
specgram Plot a spectrogram.
xcorr Plot the cross correlation between x and y.
Dr. Yusuf Perwej
Statistics
ecdf Compute and plot the empirical cumulative distribution function of x.
boxplot Draw a box and whisker plot.
violinplot Make a violin plot.

Binned
hexbin Make a 2D hexagonal binning plot of points x, y.
hist Compute and plot a histogram.
hist2d Make a 2D histogram plot.
stairs Draw a stepwise constant function as a line or a filled plot.

Contours
clabel Label a contour plot.
contour Plot contour lines.
contourf Plot filled contours.

2D arrays
imshow Display data as an image, i.e., on a 2D regular raster.
matshow Display a 2D array as a matrix in a new figure window.
pcolor Create a pseudocolor plot with a non-regular rectangular grid.
pcolormesh Create a pseudocolor plot with a non-regular rectangular grid.
spy Plot the sparsity pattern of a 2D array.
figimage Add a non-resampled image to the figure.

Unstructured triangles
triplot Draw an unstructured triangular grid as lines and/or markers.
tripcolor Create a pseudocolor plot of an unstructured triangular grid.
tricontour Draw contour lines on an unstructured triangular grid.
tricontourf Draw contour regions on an unstructured triangular grid.

Text and annotations


annotate Annotate the point xy with text text.
text Add text to the Axes.
figtext Add text to figure.
table Add a table to an Axes.
arrow Add an arrow to the Axes.
figlegend Place a legend on the figure.
legend Place a legend on the Axes.

Vector fields
barbs Plot a 2D field of wind barbs.
quiver Plot a 2D field of arrows.
quiverkey Add a key to a quiver plot.
streamplot Draw streamlines of a vector flow.
Dr. Yusuf Perwej
Axis configuration
autoscale Autoscale the axis view to the data (toggle).
axis Convenience method to get or set some axis properties.
box Turn the Axes box on or off on the current Axes.
grid Configure the grid lines.
locator_params Control behavior of major tick locators.
minorticks_off Remove minor ticks from the Axes.
minorticks_on Display minor ticks on the Axes.
rgrids Get or set the radial gridlines on the current polar plot.
thetagrids Get or set the theta gridlines on the current polar plot.
tick_params Change the appearance of ticks, tick labels, and gridlines.
ticklabel_format Configure the ScalarFormatter used by default for linear Axes.
xlabel Set the label for the x-axis.
xlim Get or set the x limits of the current Axes.
xscale Set the xaxis' scale.
xticks Get or set the current tick locations and labels of the x-axis.
ylabel Set the label for the y-axis.
ylim Get or set the y-limits of the current Axes.
yscale Set the yaxis' scale.
yticks Get or set the current tick locations and labels of the y-axis.
suptitle Add a centered suptitle to the figure.
title Set a title for the Axes.

Layout
margins Set or retrieve autoscaling margins.
subplots_adjust Adjust the subplot layout parameters.
subplot_tool Launch a subplot tool window for a figure.
tight_layout Adjust the padding between and around subplots.

Colormapping
clim Set the color limits of the current image.
colorbar Add a colorbar to a plot.
gci Get the current colorable artist.
sci Set the current image.
get_cmap Get a colormap instance, defaulting to rc values if name is None.
set_cmap Set the default colormap, and applies it to the current image if any.
imread Read an image from a file into an array.
imsave Colormap and save an array as an image file.

 Python Numpy

Numpy is a general-purpose array-processing package. It provides a high-performance multidimensional


array object, and tools for working with these arrays. It is the fundamental package for scientific

Dr. Yusuf Perwej


computing with Python. Besides its obvious scientific uses, Numpy can also be used as an efficient multi-
dimensional container of generic data.

NumPy functions are built-in functions provided by the NumPy library that operate on NumPy arrays.
These functions are designed to efficiently process large amounts of data and perform complex
calculations on multidimensional arrays. NumPy functions are designed to work with NumPy arrays and
offer superior performance compared to traditional Python functions.

 Syntax of Numpy Functions in Python

The syntax of NumPy functions in Python typically follows the following structure:
numpy.function_name (array, parameters)

where "function_name" is the name of the NumPy function, "array" is the NumPy array on which the
function is to be applied, and "parameters" are any additional parameters required by the function.

 Parameters of Numpy Functions in Python

NumPy functions in Python take one or more arrays as input and can also accept additional parameters
that modify their behavior. The parameters of NumPy functions depend on the specific function being
used. Here are some common parameters.

 axis: This parameter specifies the axis along which the function is applied. It is an optional parameter
and its default value is None. If axis is set to None, the function will be applied to the entire array.
 dtype: This parameter specifies the data type of the returned array. It is an optional parameter and its
default value is None. If dtype is set to None, the data type of the returned array will be the same as
the input array.
 out: This parameter specifies the output array where the result of the function will be stored. It is an
optional parameter and its default value is None. If out is set to None, the function will create a new
array to store the result.
 keepdims: This parameter specifies whether to keep the dimensions of the input array in the output
array. It is an optional parameter and its default value is False. If keepdims is set to True, the
dimensions of the output array will be the same as the input array. If keepdims is set to False, the
dimensions of the output array will be reduced by one.

 Return Value of Numpy Functions in Python

The return value of a NumPy function in Python depends on the specific function being used. Some
NumPy functions return a new array with the calculated results, while others modify the original array
in place. However, some NumPy functions have optional output parameters such as the ‘out’ parameter.
These functions allow you to specify an output array where the result will be stored. In this case, the
return value will be a reference to the output array rather than a new array.

 Numpy Functions in Python

Here are some of the important NumPy functions in Python which every Data scientist must know:

1. np.array(): This function is used to create an array in NumPy.

Example:
import numpy as np

Dr. Yusuf Perwej


arr = np.array([1, 2, 3])
print(arr)

Output:
[1 2 3]

Explanation: In this example, we created a numpy array by passing a list of 3 numbers as a parameter
into np.array() function.

2. np.arange(): This function is used to create an array with a range of values.

Example:
import numpy as np

arr = np.arange(1, 6)
print(arr)

Output:
[1 2 3 4 5]

Explanation: In this example, we created a numpy array with a range of values which is (1,6), where 6
is excluded.

3. np.zeros(): This function is used to create an array filled with zeros.

Example:
import numpy as np

arr = np.zeros(3)
print(arr)

Output:
[0. 0. 0.]

Explanation: In this example, we created an array of size 3 which is filled with only zeroes.

4. np.ones(): This function is used to create an array filled with ones.

Example:
import numpy as np

arr = np.ones(3)
print(arr)

Output:
[1. 1. 1.]

Explanation: In this example, we created an array of size 3 which is filled with only ones.

5. np.linspace(): This function is used to create an array with a specified number of evenly spaced
values.

Dr. Yusuf Perwej


Example:
import numpy as np

arr = np.linspace(0, 1, 5)
print(arr)

Output:
[0. 0.25 0.5 0.75 1. ]

6. np.random.rand(): This function is used to create an array with random values between 0 and 1.

Example:
import numpy as np

arr = np.random.rand(3)
print(arr)

Output:
[0.5488135 0.71518937 0.60276338]

Explanation: In this example, we created an array of size 3 which is filled with random values which
lie between 0 and 1.

7. np.random.randint(): This function is used to create an array with random integer values between a
specified range.

Example:
import numpy as np

arr = np.random.randint(0, 10, 5)


print(arr)

Output:
[1 5 8 9 8]

Explanation: In this example, we created an array of size 5 which is filled with random values which
lie between 0 and 10.

8. np.max(): This function is used to find the maximum value in an array.

Example:
import numpy as np

arr = np.array([1, 2, 3])


max_value = np.max(arr)
print(max_value)

Output:
3

Explanation: In this example, we used max() function to find the max element in our array, which is 3
in this case.
Dr. Yusuf Perwej
9. np.min(): This function is used to find the minimum value in an array.

Example:
import numpy as np

arr = np.array([1, 2, 3])


min_value = np.min(arr)
print(min_value)

Output:
1

Explanation: In this example, we used min() function to find the min element in our array, which is 1
in this case.

10. np.mean(): This function is used to find the mean value of an array.

Example:
import numpy as np

arr = np.array([1, 2, 3])


mean_value = np.mean(arr)
print(mean_value)

Output:
2.0

11. np.median(): This function is used to find the median value of an array.

Example:
import numpy as np

arr = np.array([1, 2, 3])


median_value = np.median(arr)
print(median_value)

Output:
2.0

12. np.dot(): This function is used to find the dot product of two arrays.

Example:
import numpy as np

arr1 = np.array([1, 2, 3])


arr2 = np.array([4, 5, 6])

dot_product = np.dot(arr1, arr2)


print(dot_product)
Output:
32
Dr. Yusuf Perwej
Explanation: In this example, we created two NumPy arrays called array1 and array2, which contain
the values [1, 2, 3] and [4, 5, 6], respectively. We then used np.dot() to calculate the dot product of
these two arrays, which is equal to 14 + 25 + 3*6, or 32. The resulting value is stored in the variable
result and printed to the console.

 Summary

 NumPy is a Python library for numerical computing that provides powerful data structures and
functions for scientific computing tasks.
 NumPy arrays are the primary data structure used in NumPy, and they can be one-dimensional
or multi-dimensional.
 NumPy functions are used to create, manipulate, and analyze NumPy arrays.
 The syntax of NumPy functions generally involves calling the function and passing one or more
parameters, such as the shape of the array, the range of values to generate, or the type of data to
use.
 The return value of NumPy functions can be an array, a scalar value, or a tuple of values.
 Some important NumPy functions include np.array(), np.arange(), np.zeros(), np.ones(),
np.linspace(), and np.random.rand().
 These functions can be used to create NumPy arrays with specific shapes, ranges of values, and
data types.
 NumPy functions are powerful tools for data analysis and scientific computing, and they are
essential for many applications in fields such as physics, engineering, and data science.

 Using the NumPy functions

NumPy has a variety of built-in functions to create an array.

a. Creating one-dimensional array in NumPy

For 1-D arrays the most common function is np.arange(..), passing any value create an array from 0 to
that number.

Example:
import numpy as np
array=np.arange(20)
array

Output:
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12, 13, 14, 15, 16, 17, 18, 19])

We can check the dimensions by using array.shape.

Output:
(20,)

To access the element of the array we can specify its non-negative index.
array[3]

Output:
3

Dr. Yusuf Perwej


b. Creating two-dimensional arrays in NumPy

We can use reshape()function along with the arange() function to create a 2D array. The
reshape()function specifies the rows and columns.

Example:
array=np.arange(20).reshape(4,5)

Output:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]
[15, 16, 17, 18, 19]])

In 2-D arrays to access the elements, we will require to specify two values for row and column
respectively.

Similarly, we can create 3-D and more by increasing the number of parameters in the
reshape()function.

c. Using other NumPy functions

We can use other functions like and to quickly create filled arrays.

Example:
np.zeros((2,4))
np.ones((3,6))

Output:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.]])array([[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.]])

The .empty() function creates an array with random variables and the full() function creates an n*n
array with the given value

Example:
np.empty((2,3))
np.full((2,2), 3)

Output:
array([[2.69893675e-316, 0.00000000e+000, 0.00000000e+000],
[0.00000000e+000, 0.00000000e+000, 0.00000000e+000]])
array([[3, 3],
[3, 3]])

The .eye( , )function creates an array with diagonals as 1 and other values as 0. The .linspace(, ,)
function outputs an equally spaced array.

Example:
np.eye(3,3)
Dr. Yusuf Perwej
np.linspace(0, 10, num=4)

Output:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
array([ 0. , 3.33333333, 6.66666667, 10. ])

Function Description
empty_like() Return a new array with the same shape and type
ones_like() Return an array of ones with the same shape and type.
zeros_like() Return an array of zeros with the same shape and type
full_like() Return a full array with the same shape and type
asarray() Convert the input to an array.
geomspace() Return evenly spaced numbers on a log scale.
copy() Returns a copy of the given object
diag() a diagonal array
frombuffer() buffer as a 1-D array
fromfile() Construct an array from text or binary file
bmat() Build a matrix object from a string, nested sequence, or array
mat() Interpret the input as a matrix
vander() Generate a Vandermonde matrix
triu() Upper triangle of array
tril() Lower triangle of array
tri() An array with ones at & below the given diagonal and zeros elsewhere
diagflat() two-dimensional array with the flattened input as a diagonal
fromfunction() executing a function over each coordinate
logspace() Return numbers spaced evenly on a log scale
meshgrid() Return coordinate matrices from coordinate vectors

 Conversion from Python structure like lists

We can use the Python lists to create arrays by passing a list to the array function. We can also directly
create an array of elements by passing a list.

Example:
array=np.array([4,5,6])
array
list=[4,5,6]
list

Output:
array([4, 5, 6])[4, 5, 6]
To create 2-D or more we pass a sequence of lists.

 Using other library functions

Dr. Yusuf Perwej


We can use the function to create an array with random values between 0 and 1. This is a useful case in
scenarios with random nature.

Example:
np.random.random((2,3))

Output:
array([[0.42593659, 0.91495384, 0.05727104],
[0.3754818 , 0.63166016, 0.5901392 ]])

 NumPy Array Indexing

Indexing of the array has to be proper in order to access and manipulate its values. Indexing can be
done through:

 Slicing – we perform slicing on NumPy arrays with the declaration of a slice for all the
dimensions.
 Integer array Indexing– users can pass lists for one to one mapping of corresponding elements
for each dimension.
 Boolean Array Indexing– we can pick elements after satisfying a particular Boolean condition.

 NumPy Basic Array Operations

There is a vast range of built-in operations that we can perform on these arrays.

 ndim – It returns the dimensions of the array.


 itemsize – It calculates the byte size of each element
 dtype – It can determine the data type of the element
 reshape – It provides a new view
 slicing – It extracts a particular set of elements.
 linspace – Returns evenly spaced elements.
 max/min , sum, sq
 ravel – It converts the array into a single line.

There are also a few Special Operations like sine, cosine, tan, log, etc.

 Checking Array Dimensions in NumPy

We can determine the NumPy array dimensions using the ndim attribute. The argument return an
integer that indicates the array dimension.

Example:
import numpy as np
a = np.array(10)
b = np.array([1,1,1,1])
c = np.array([[1, 1, 1], [2,2,2]])
d = np.array([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
Dr. Yusuf Perwej
Output:
0123

 Higher Dimensional Arrays in NumPy

In Numpy we can have arrays with any number of dimensions. There can be arrays with a high number
of dimensions. We define the number of dimensions with the ndim argument.

Example:
import numpy as np
arr = np.array([1, 1, 1, 1, 1], ndmin=10)
print(arr)
print('number of dimensions :', arr.ndim)

Output:
[[[[[[[[[[1 1 1 1 1]]]]]]]]]] number of dimensions : 10

In the above example, the innermost dimension (10th dim) has 5 elements, the 9th dim has 1 element
that is the vector, the 8th dim has 1 element that is the matrix with the vector, the 7th dim has 1 element
that is 3D array 6th dim has 1 element that is a 4D array and so on.
Indexing and Slicing in NumPy

These are two very important concepts. It is useful when we want to work with sub-arrays.
Indexing starts with zero as the first index. We can retrieve element values by its index value. For 2 or
more dimensional arrays, we have to specify 2 or more indices. Indexing can be of two types

1. Integer array indexing


We pass lists for indexing in all the dimensions. Then one to one mapping occurs for the creation of a
new array.

2. Boolean array indexing


In this type of indexing, we carry out a condition check. If the boolean condition satisfies we create an
array of those elements.

Example:
import numpy as np
arr=([1,2,5,6,7])
arr[3]

Output:
6

Slicing is similar to indexing, but it retrieves a string of values. The range is defined by the starting and
ending indices. It is similar to lists in Python. The arrays can also be sliced. The arrays can be single or
multidimensional. We can specify slices for all the dimensions.

Example:
import numpy as np
arr=([1,2,5,6,7])
arr[2:5]

Dr. Yusuf Perwej


Output:
[5, 6, 7]

 Advanced Methods on Arrays in NumPy

A few advanced methods available for NumPy Arrays are -:

1. Staking (along different axes) – Horizontally, Vertically, as columns and we can also perform
concatenation along a specific axis.
2. Splitting – Array can be split along horizontal, vertical, or along a specific axis.
3. Broadcasting – with this method we can convert arrays to have compatible shapes to perform
arithmetic operations. In order to broadcast the trailing axes should be either the same or one of them
should be one.
4. DateTime – NumPy has its own DateTime data type like python’s inbuilt named datetime64.
5. Linear algebra – we can perform linear algebra on arrays using this module.

 Pandas

Pandas is a powerful and open-source Python library. The Pandas library is used for data manipulation
and analysis. Pandas consist of data structures and functions to perform efficient operations on data.

It was created in 2008 by Wes McKinney and is used for data analysis in Python. Pandas is an open-
source library that provides high-performance data manipulation in Python. All of the basic and
advanced concepts of Pandas, such as Numpy, data operation, and time series, are covered in our
tutorial.

Pandas is one of the most used libraries in Python for data science or data analysis. It can read data
from CSV or Excel files, manipulate the data, and generate insights from it. Pandas can also be used to
clean data, processing, such as restructuring, filter data, merging, and visualize data.

Numpy, Scipy, Cython, and Panda are just a few of the fast data processing tools available. Since
Pandas is built on top of the Numpy bundle, it is expected that Numpy will work with Pandas.

Before Pandas, Python was able for information planning, however it just offered restricted help for
information investigation. As a result, Pandas entered the picture and enhanced data analysis
capabilities. Regardless of the source of the data, it can carry out the five crucial steps that are
necessary for processing and analyzing it: load, manipulate, prepare, model, and analyze.

 Key Features of Pandas

 It has a DataFrame object that is quick and effective, with both standard and custom indexing.
 Utilized for reshaping and turning of the informational indexes.
 For aggregations and transformations, group by data.
 It is used to align the data and integrate the data that is missing.
 Provide Time Series functionality.
 Process a variety of data sets in various formats, such as matrix data, heterogeneous tabular
data, and time series.
 Manage the data sets' multiple operations, including subsetting, slicing, filtering, groupBy,
reordering, and reshaping.
 It incorporates with different libraries like SciPy, and scikit-learn.
 Performs quickly, and the Cython can be used to accelerate it even further.

Dr. Yusuf Perwej


 Benefits of Pandas

Representation of Data: Through its DataFrame and Series, it presents the data in a manner that is
appropriate for data analysis.
Clear code: Pandas' clear API lets you concentrate on the most important part of the code. In this way,
it gives clear and brief code to the client.
DataFrame and Series are the two data structures that Pandas provides for processing data.

 Series: A one-dimensional array capable of storing a variety of data types is how it is defined. The
term "index" refers to the row labels of a series. We can without much of a stretch believer the
rundown, tuple, and word reference into series utilizing "series' technique. Multiple columns cannot
be included in a Series. Only one parameter exists:
 Data: It can be any list, dictionary, or scalar value.

 Creating Series from Array:

Before creating a Series, Firstly, we have to import the numpy module and then use array() function in
the program.

Example:
import pandas as pd
import numpy as np
info = np.array(['P','a','n','d','a','s'])
a = pd.Series(info)
print(a)

Output:
0 P
1 a
2 n
3 d
4 a
5 s
dtype: object

Explanation: In this code, firstly, we have imported the pandas and numpy library with the pd and
np alias. Then, we have taken a variable named "info" that consist of an array of some values. We have
called the info variable through a Series method and defined it in an "a" variable. The Series has
printed by calling the print(a) method.

 Pandas DataFrame

It is a generally utilized information design of pandas and works with a two-layered exhibit with named
tomahawks (lines and segments). As a standard method for storing data, DataFrame has two distinct
indexes-row index and column index.

The sections can be heterogeneous sorts like int, bool, etc. It can be thought of as a series structure
dictionary with indexed rows and columns. It is referred to as "columns" for rows and "index" for
columns.

 Create a DataFrame using List

Dr. Yusuf Perwej


We can easily create a DataFrame in Pandas using list.

Example:
import pandas as pd
# a list of strings
x = ['Python', 'Pandas']

# Calling DataFrame constructor on list


df = pd.DataFrame(x)
print(df)

Output:
0
0 Python
1 Pandas

Explanation: In this code, we have characterized a variable named "x" that comprise of string values.
On a list, the values are being printed by calling the DataFrame constructor.

 Python Pandas Series

The Pandas Series can be defined as a one-dimensional array that is capable of storing various data
types. We can easily convert the list, tuple, and dictionary into series using "series' method. The row
labels of series are called the index. A Series cannot contain multiple columns. It has the following
parameter:

 data: It can be any list, dictionary, or scalar value.


 index: The value of the index should be unique and hashable. It must be of the same length as
data. If we do not pass any index, default np.arrange(n) will be used.
 dtype: It refers to the data type of series.
 copy: It is used for copying the data.

 Creating a Series

We can create a Series in two ways:

 Create an empty Series


 Create a Series using inputs.

 Create an Empty Series

We can easily create an empty series in Pandas which means it will not have any value.
The syntax that is used for creating an Empty Series:

 <series object> = pandas.Series()

The below example creates an Empty Series type object that has no values and having default datatype,
i.e.,

Example:
import pandas as pd
Dr. Yusuf Perwej
x = pd.Series()
print (x)

Output:
Series([], dtype: float64)

 Creating a Series using inputs

We can create Series by using various inputs

 Array
 Dict
 Scalar value

 Creating Series from Array

Before creating a Series, firstly, we have to import the numpy module and then use array() function in
the program. If the data is ndarray, then the passed index must be of the same length.

If we do not pass an index, then by default index of range(n) is being passed where n defines the
length of an array, i.e., [0,1,2,....range(len(array))-1].

Example:
import pandas as pd
import numpy as np
info = np.array(['P','a','n','d','a','s'])
a = pd.Series(info)
print(a)

Output:
0 P
1 a
2 n
3 d
4 a
5 s
dtype: object

 Create a Series from dict

We can also create a Series from dict. If the dictionary object is being passed as an input and the
index is not specified, then the dictionary keys are taken in a sorted order to construct the index.
If index is passed, then values correspond to a particular label in the index will be extracted from the
dictionary.

Example:
#import the pandas library
import pandas as pd
import numpy as np
info = {'x' : 0., 'y' : 1., 'z' : 2.}
a = pd.Series(info)
print (a)
Dr. Yusuf Perwej
Output:
x 0.0
y 1.0
z 2.0
dtype: float64

 Create a Series using Scalar

If we take the scalar values, then the index must be provided. The scalar value will be repeated for
matching the length of the index.

Example:
#import pandas library
import pandas as pd
import numpy as np
x = pd.Series(4, index=[0, 1, 2, 3])
print (x)

Output:
0 4
1 4
2 4
3 4
dtype: int64

 Accessing data from series with Position:

Once you create the Series type object, you can access its indexes, data, and even individual elements.
The data in the Series can be accessed similar to that in the ndarray.

Example:
import pandas as pd
x = pd.Series([1,2,3],index = ['a','b','c'])
#retrieve the first element
print (x[0])

Output:
1

 Series object attributes

The Series attribute is defined as any information related to the Series object such as size, datatype. etc.
Below are some of the attributes that you can use to get the information about the Series object.

Attributes Description
Series.index Defines the index of the Series.
Series.shape It returns a tuple of shape of the data.
Series.dtype It returns the data type of the data.
Series.size It returns the size of the data.
Series.empty It returns True if Series object is empty, otherwise returns false.
Dr. Yusuf Perwej
Series.hasnans It returns True if there are any NaN values, otherwise returns false.
Series.nbytes It returns the number of bytes in the data.
Series.ndim It returns the number of dimensions in the data.
Series.itemsize It returns the size of the datatype of item.
 Retrieving Index array and data array of a series object

We can retrieve the index array and data array of an existing Series object by using the attributes index
and values.

Example:
import numpy as np
import pandas as pd
x=pd.Series(data=[2,4,6,8])
y=pd.Series(data=[11.2,18.6,22.5], index=['a','b','c'])
print(x.index)
print(x.values)
print(y.index)
print(y.values)

Output:
RangeIndex(start=0, stop=4, step=1)
[2 4 6 8]
Index(['a', 'b', 'c'], dtype='object')
[11.2 18.6 22.5]

 Retrieving Types (dtype) and Size of Type (itemsize)

You can use attribute dtype with Series object as <objectname> dtype for retrieving the data type of an
individual element of a series object, you can use the itemsize attribute to show the number of bytes
allocated to each data item.

Example:
import numpy as np
import pandas as pd
a=pd.Series(data=[1,2,3,4])
b=pd.Series(data=[4.9,8.2,5.6],
index=['x','y','z'])
print(a.dtype)
print(a.itemsize)
print(b.dtype)
print(b.itemsize)

Output:
int64
8
float64
8

 Retrieving Shape

Dr. Yusuf Perwej


The shape of the Series object defines total number of elements including missing or empty
values(NaN).

Example:
import numpy as np
import pandas as pd
a=pd.Series(data=[1,2,3,4])
b=pd.Series(data=[4.9,8.2,5.6],index=['x','y','z'])
print(a.shape)
print(b.shape)

Output:
(4,)
(3,)

 Retrieving Dimension, Size and Number of bytes

Example:
import numpy as np
import pandas as pd
a=pd.Series(data=[1,2,3,4])
b=pd.Series(data=[4.9,8.2,5.6],
index=['x','y','z'])
print(a.ndim, b.ndim)
print(a.size, b.size)
print(a.nbytes, b.nbytes)

Output:
11
43
32 24

 Checking Emptiness and Presence of NaNs

To check the Series object is empty, you can use the empty attribute. Similarly, to check if a series
object contains some NaN values or not, you can use the hasans attribute.
Example:
import numpy as np
import pandas as pd
a=pd.Series(data=[1,2,3,np.NaN])
b=pd.Series(data=[4.9,8.2,5.6],index=['x','y','z'])
c=pd.Series()
print(a.empty,b.empty,c.empty)
print(a.hasnans,b.hasnans,c.hasnans)
print(len(a),len(b))
print(a.count( ),b.count( ))

Output:
False False True
True False False
4 3
3 3
Dr. Yusuf Perwej
 Series Functions

There are some functions used in Series which are as follows:

Functions Description
Pandas Series.map() Map the values from two series that have a common column.
Calculate the standard deviation of the given set of numbers,
Pandas Series.std()
DataFrame, column, and rows.
Pandas Series.to_frame() Convert the series object to the dataframe.
Pandas
Returns a Series that contain counts of unique values.
Series.value_counts()

 List of Important Pandas Functions

Function Description
Pandas read_csv() This function is used to retrieve data from CSV files in the form of a
Function dataframe.
This function is used to return the top n (5 by default) values of a data frame
Pandas head() Function
or series.
This method is used to return the bottom n (5 by default) rows of a data
Pandas tail() Function
frame or series.
Pandas sample() This method is used to generate a sample random row or column from the
Function data frame.
This method is used to generate the summary of the DataFrame, this will
Pandas info() Function include info about columns with their names, their datatypes, and missing
values.
Pandas dtypes()
This method returns a Series with the data type of each column.
Function
Pandas shape() Function It returns a tuple representing the dimensionality of the Pandas DataFrame.
This method returns the number of rows in the Series. Otherwise, return the
Pandas size() Function
number of rows times the number of columns in the DataFrame.
Pandas ndim() Function This function returns 1 if Series and 2 if DataFrame
Pandas describe() Returns descriptive statistics about the data like mean, minimum,
Function maximum, standard deviation, etc.
Pandas unique()
It returns all the unique values in a particular column.
Function
Pandas nunique()
Returns the number of unique values in the column
Function
Returns the DataFrame/Series of the boolean values. Missing values gets
Pandas isnull() Function
mapped to True and non-missing value gets mapped to False.
Python isna() Function Returns dataframe/series with bool values. Missing values gets mapped to
True and non-missing gets mapped to False.
This function is used to trim values at a specified input threshold.
Pandas fillna() Function

Dr. Yusuf Perwej


Function Description
Returns index information of the DataFrame.
Pandas clip() Function
Pandas columns() Returns column names of the dataframe
Function
Pandas sort_values() This method sorts the data frame in ascending or descending order of
Function passed Column.
Returns the counts of the unique values in a series or from a dataframe’s
Pandas value_counts()
column
Function
Pandas nlargest()
Used to get n largest values from a data frame or a series.
Function
Pandas nsmallest()
Used to get n smallest values from a data frame or a series.
Function
To copy DataFrame in Pandas.
Pandas copy() Function
Used to access a group of rows and columns by label(s) or a boolean array
Pandas loc() Function
in the given dataframe.
This method is used to retrieve rows from a dataframe.
Pandas iloc() Function
Pandas rename()
This method is used to rename any index, column, or row.
Function
This method is used to check a data frame for one or more conditions and
Pandas where() Function
return the result accordingly.
Used to drop rows/columns from a dataframe.
Pandas drop() Function
Pandas groupby() Used to group data based on some criteria.
Function
This function is used to find the correlation among the columns in the
Pandas corr() Function
Dataframe.
Pandas query() Function
To filter dataframe based on a certain condition.
This method allows us to insert a column at any position.
Pandas insert() Function
Pandas sum() Function
It returns the sum of the values for the requested axis.
Pandas mean() Function It returns the mean of the values for the requested axis.
Pandas median()
It returns the median of the values for the requested axis.
Function
Pandas std() Function It returns sample standard deviation over the requested axis.
Pandas apply() Function Using this we can apply a function to every row in the given dataframe.
Pandas merge()
Used to merge two Pandas dataframes.
Function
Pandas astype()
This method is used to cast pandas object to a specified dtype.
Function
Pandas set_index() This method is used to set a List, Series or Data frame as an index of a Data
Function Frame.
Dr. Yusuf Perwej
Function Description
Pandas reset_index()
This method is used to reset the index of a Data Frame.
Function
Pandas at() Function This method is used to return data in a dataframe at the passed location.
Pandas iterrows() This function is used to iterate over Pandas Dataframe rows in the form of
Function (index, series) pair.
Pandas iteritems()
This function iterates over the given series object.
Function
Pandas to_datetime() This method helps to convert the string Date time into a Python Date time
Function object.
Pandas to_numeric()
This method is used to convert an argument to a numeric type.
Function
Pandas to_string() This method is used to render the given DataFrame to a console-friendly
Function tabular output.
Pandas concat()
This function is used to concatenate dataframes along a particular axis.
Function
Pandas cov() Function This method is used to compute the pairwise covariance of columns.
Pandas duplicated() This method helps in analyzing duplicate values only. It returns a boolean
Function series which is True only for Unique elements.
Pandas
drop_duplicates() This method removes the duplicates from Pandas’s dataframe.
Function
Pandas dropna()
This method helps in dropping Rows/Columns with Null values
Function
This method is used to find the first discrete difference of objects over the
Pandas diff() Function
given axis.
This method returns a rank of every respective index of a series passed. The
Pandas rank() Function
rank is returned on the basis of position after sorting.

Pandas resample()
This method is used to resample the Time Series data.
Function
Pandas transform() This function calls a function on self-producing a DataFrame with
Function transformed values that have the same axis length as self.
Pandas replace()
This function is used to replace values.
Function
Pandas to_csv() This function is used to write series/dataframe objects to comma-separated
Function values (csv) files.
Pandas to_excel()
This method is used to export the DataFrame to the Excel file.
Function
Pandas_to_sql()
This function is used to write the given dataframe to a SQL database.
Function
Pandas plot() Function This method is used to plot dataframe.

Dr. Yusuf Perwej


 Tkinter

Tkinter is a standard Python GUI (Graphical User Interface) library that provides a set of tools and
widgets to create desktop applications with graphical interfaces. Tkinter is included with most Python
installations, making it easily accessible for developers who want to build GUI applications without
requiring additional installations or libraries.

 Full Form of Tkinter

The name “Tkinter” comes from “Tk interface“, referring to the Tk GUI toolkit that Tkinter is based
on. Tkinter provides a way to create windows, buttons, labels, text boxes, and other GUI components to
build interactive applications.

 Significance of Tkinter

Tkinter is the inbuilt python module that is used to create GUI applications. It is one of the most
commonly used modules for creating GUI applications in Python as it is simple and easy to work with.
You don’t need to worry about the installation of the Tkinter module separately as it comes with Python
already. It gives an object-oriented interface to the Tk GUI toolkit. Among all, Tkinter is most widely
used

 Where is Python Tkinter used

Here are some common use cases for Tkinter:

1. Creating windows and dialog boxes: Tkinter can be used to create windows and dialog boxes
that allow users to interact with your program. These can be used to display information, gather
input, or present options to the user.

2. Building a GUI for a desktop application: Tkinter can be used to create the interface for a
desktop application, including buttons, menus, and other interactive elements.

3. Adding a GUI to a command-line program: Tkinter can be used to add a GUI to a command-
line program, making it easier for users to interact with the program and input arguments.

4. Creating custom widgets: Tkinter includes a variety of built-in widgets, such as buttons, labels,
and text boxes, but it also allows you to create your own custom widgets.

5. Prototyping a GUI: Tkinter can be used to quickly prototype a GUI, allowing you to test and
iterate on different design ideas before committing to a final implementation.

 Fundamental structure of Tkinter program

Dr. Yusuf Perwej


Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods,
tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped
with Python. Python Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI
using Tkinter is an easy task.

 Create First Tkinter GUI Application

There are two main methods used which the user needs to remember while creating the Python
application with GUI.

 Tk()

To create a main window, tkinter offers a method


‘Tk(screenName=None, baseName=None, className=’Tk’, useTk=1)’. To change the name of the
window, you can change the className to the desired one. The basic code used to create the main
window of the application is.

 mainloop()

There is a method known by the name mainloop() is used when your application is ready to run.
mainloop() is an infinite loop used to run the application, wait for an event to occur, and process the
event as long as the window is not closed.

Example:
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()

Output:

Dr. Yusuf Perwej


 Tkinter Widget

There are a number of widgets which you can put in your tkinter application. Some of the major widgets
are explained below.

1. Label
It refers to the display box where you can put any text or image which can be updated any time as per
the code. The general syntax is:

w=Label(master, option=value)
master is the parameter used to represent the parent window.

Example:
from tkinter import *
root = Tk()
w = Label(root, text='Goel.org!')
w.pack()
root.mainloop()

Output:

2. Button

To add a button in your application, this widget is used. The general syntax is:
w=Button(master, option=value)

master is the parameter used to represent the parent window. There are number of options which are
used to change the format of the Buttons. Number of options can be passed as parameters separated by
commas.

Example:
import tkinter as tk

r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()

Output:

3. Entry

Dr. Yusuf Perwej


It is used to input the single line text entry from the user.. For multi-line text input, Text widget is used.
The general syntax is:
w=Entry(master, option=value)

master is the parameter used to represent the parent window. There are number of options which are
used to change the format of the widget. Number of options can be passed as parameters separated by
commas.

Example:
from tkinter import *
master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()

Output:

4. CheckButton

To select any number of options by displaying a number of options to a user as toggle buttons. The
general syntax is:
w = CheckButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

master = Tk()
var1 = IntVar()
Checkbutton(master, text='male', variable=var1).grid(row=0, sticky=W)
var2 = IntVar()
Checkbutton(master, text='female', variable=var2).grid(row=1, sticky=W)
mainloop()

Output:

5. RadioButton

Dr. Yusuf Perwej


It is used to offer multi-choice option to the user. It offers several options to the user and the user has to
choose one option. The general syntax is:
w = RadioButton(master, option=value)

There are number of options which are used to change the format of this widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

root = Tk()
v = IntVar()
Radiobutton(root, text='GfG', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='MIT', variable=v, value=2).pack(anchor=W)
mainloop()

Output:

6. Listbox

It offers a list to the user from which the user can accept any number of options. The general syntax is:
w = Listbox(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
top.mainloop()

Output:

Dr. Yusuf Perwej


7. Scrollbar

It refers to the slide controller which will be used to implement listed widgets. The general syntax is:
w = Scrollbar(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

root = Tk()
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
mylist = Listbox(root, yscrollcommand=scrollbar.set)

for line in range(100):


mylist.insert(END, 'This is line number' + str(line))

mylist.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=mylist.yview)
mainloop()
Output:

8. Menu

It is used to create all kinds of menus used by the application. The general syntax is:
w = Menu(master, option=value)

Dr. Yusuf Perwej


master is the parameter used to represent the parent window.
There are number of options which are used to change the format of this widget. Number of options can
be passed as parameters separated by commas..

Example:
from tkinter import *

root = Tk()
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New')
filemenu.add_command(label='Open...')
filemenu.add_separator()
filemenu.add_command(label='Exit', command=root.quit)
helpmenu = Menu(menu)
menu.add_cascade(label='Help', menu=helpmenu)
helpmenu.add_command(label='About')
mainloop()
Output:

9. Combobox

Combobox widget is created using the ttk.Combobox class from the tkinter.ttk module. The values for
the Combobox are specified using the values parameter. The default value is set using the set method.
An event handler function on_select is bound to the Combobox using the bind method, which updates a
label with the selected item whenever an item is selected.

Example:
import tkinter as tk
from tkinter import ttk

def on_select(event):
selected_item = combo_box.get()
label.config(text="Selected Item: " + selected_item)

root = tk.Tk()
root.title("Combobox Example")

# Create a label
Dr. Yusuf Perwej
label = tk.Label(root, text="Selected Item: ")
label.pack(pady=10)

# Create a Combobox widget


combo_box = ttk.Combobox(root, values=["Option 1", "Option 2", "Option 3"])
combo_box.pack(pady=5)

# Set default value


combo_box.set("Option 1")

# Bind event to selection


combo_box.bind("<<ComboboxSelected>>", on_select)

root.mainloop()

Output:

10. Scale

It is used to provide a graphical slider that allows to select any value from that scale. The general
syntax is:
w = Scale(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

master = Tk()
w = Scale(master, from_=0, to=42)
w.pack()
w = Scale(master, from_=0, to=200, orient=HORIZONTAL)
w.pack()
mainloop()

Output:

Dr. Yusuf Perwej


11. TopLevel

This widget is directly controlled by the window manager. It don’t need any parent window to work
on.The general syntax is:
w = TopLevel(master, option=value)

There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

root = Tk()
root.title('GfG')
top = Toplevel()
top.title('Python')
top.mainloop()

Output:

12. Message

It refers to the multi-line and non-editable text. It works same as that of Label. The general syntax is:
w = Message(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

Dr. Yusuf Perwej


main = Tk()
ourMessage = 'This is our Message'
messageVar = Message(main, text=ourMessage)
messageVar.config(bg='lightgreen')
messageVar.pack()
main.mainloop()

Output:

13. MenuButton

It is a part of top-down menu which stays on the window all the time. Every menubutton has its own
functionality. The general syntax is:
w = MenuButton(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

top = Tk()
mb = Menubutton ( top, text = "GfG")
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
cVar = IntVar()
aVar = IntVar()
mb.menu.add_checkbutton ( label ='Contact', variable = cVar )
mb.menu.add_checkbutton ( label = 'About', variable = aVar )
mb.pack()
top.mainloop()

Output:

14. Progressbar

Tkinter application with a Progressbar widget and a button to start the progress. When the button is
clicked, the progressbar fills up to 100% over a short period, simulating a task that takes time to
complete.

Example:
Dr. Yusuf Perwej
import tkinter as tk
from tkinter import ttk
import time

def start_progress():
progress.start()

# Simulate a task that takes time to complete


for i in range(101):
# Simulate some work
time.sleep(0.05)
progress['value'] = i
# Update the GUI
root.update_idletasks()
progress.stop()

root = tk.Tk()
root.title("Progressbar Example")

# Create a progressbar widget


progress = ttk.Progressbar(root, orient="horizontal", length=300, mode="determinate")
progress.pack(pady=20)

# Button to start progress


start_button = tk.Button(root, text="Start Progress", command=start_progress)
start_button.pack(pady=10)

root.mainloop()

Output:

15. SpinBox

It is an entry of ‘Entry’ widget. Here, value can be input by selecting a fixed value of numbers.The
general syntax is:
w = SpinBox(master, option=value)

There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

master = Tk()
w = Spinbox(master, from_=0, to=10)
Dr. Yusuf Perwej
w.pack()
mainloop()

Output:

16. Text

To edit a multi-line text and format the way it has to be displayed. The general syntax is:
w =Text(master, option=value)

There are number of options which are used to change the format of the text. Number of options can be
passed as parameters separated by commas.

Example:
from tkinter import *

root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'GITM\nBEST WEBSITE\n')
mainloop()

Output:

17. Canvas

It is used to draw pictures and other complex layout like graphics, text and widgets. The general syntax
is:
w = Canvas(master, option=value)

master is the parameter used to represent the parent window.


There are number of options which are used to change the format of the widget. Number of options can
be passed as parameters separated by commas.

Example:
from tkinter import *

master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
Dr. Yusuf Perwej
Output:

18. PannedWindow

It is a container widget which is used to handle number of panes arranged in it. The general syntax is:
w = PannedWindow(master, option=value)

Master is the parameter used to represent the parent window. There are number of options which are
used to change the format of the widget. Number of options can be passed as parameters separated by
commas.

Example:
from tkinter import *

m1 = PanedWindow()
m1.pack(fill=BOTH, expand=1)
left = Entry(m1, bd=5)
m1.add(left)
m2 = PanedWindow(m1, orient=VERTICAL)
m1.add(m2)
top = Scale(m2, orient=HORIZONTAL)
m2.add(top)
mainloop()

Output:

 Color Option in Tkinter

This example demonstrates the usage of various color options in Tkinter widgets, including active
background and foreground colors, background and foreground colors, disabled state colors, and
selection colors. Each widget in the example showcases a different color option, providing a visual
representation of how these options affect the appearance of the widgets.

Example:
import tkinter as tk

root = tk.Tk()
root.title("Color Options in Tkinter")

# Create a button with active background and foreground colors


button = tk.Button(root, text="Click Me", activebackground="blue", activeforeground="white")
button.pack()
Dr. Yusuf Perwej
# Create a label with background and foreground colors
label = tk.Label(root, text="Hello, Tkinter!", bg="lightgray", fg="black")
label.pack()

# Create an Entry widget with selection colors


entry = tk.Entry(root, selectbackground="lightblue", selectforeground="black")
entry.pack()

root.mainloop()

Output:

 Geometry Management

Tkinter also offers access to the geometric configuration of the widgets which can organize the widgets
in the parent windows. There are mainly three geometry manager classes class.

 pack() method

It organizes the widgets in blocks before placing in the parent widget.

Example:
import tkinter as tk

root = tk.Tk()
root.title("Pack Example")

# Create three buttons


button1 = tk.Button(root, text="Button 1")
button2 = tk.Button(root, text="Button 2")
button3 = tk.Button(root, text="Button 3")

# Pack the buttons vertically


button1.pack()
button2.pack()
button3.pack()

root.mainloop()

Output:

Dr. Yusuf Perwej


 grid() method

It organizes the widgets in grid (table-like structure) before placing in the parent widget.

Example:
import tkinter as tk

root = tk.Tk()
root.title("Grid Example")

# Create three labels


label1 = tk.Label(root, text="Label 1")
label2 = tk.Label(root, text="Label 2")
label3 = tk.Label(root, text="Label 3")

# Grid the labels in a 2x2 grid


label1.grid(row=0, column=0)
label2.grid(row=0, column=1)
label3.grid(row=1, column=0, columnspan=2)

root.mainloop()

Output:

 place() method

It organizes the widgets by placing them on specific positions directed by the programmer.

Example:
import tkinter as tk

root = tk.Tk()
root.title("Place Example")

# Create a label
label = tk.Label(root, text="Label")

# Place the label at specific coordinates


label.place(x=50, y=50)
Dr. Yusuf Perwej
root.mainloop()
Output:

 Tkinter widgets

There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build the python
GUI applications.

Widget Description
Button The Button is used to add various kinds of buttons to the python application.
Canvas The canvas widget is used to draw the canvas on the window.
Checkbutton The Checkbutton is used to display the CheckButton on the window.
The entry widget is used to display the single-line text field to the user. It is commonly
Entry
used to accept user values.
Frame It can be defined as a container to which, another widget can be added and organized.
Label A label is a text used to display some message or information about the other widgets.
ListBox The ListBox widget is used to display a list of options to the user.
Menubutton The Menubutton is used to display the menu items to the user.
Menu It is used to add menu items to the user.
Message The Message widget is used to display the message-box to the user.
The Radiobutton is different from a checkbutton. Here, the user is provided with
Radiobutton
various options and the user can select only one option among them.
Scale It is used to provide the slider to the user.
It provides the scrollbar to the user so that the user can scroll the window up and
Scrollbar
down.
It is different from Entry because it provides a multi-line text field to the user so that
Text
the user can write the text and edit the text inside it.
Toplevel It is used to create a separate window container.
Spinbox It is an entry widget used to select from options of values.
PanedWindow It is like a container widget that contains horizontal or vertical panes.
LabelFrame A LabelFrame is a container widget that acts as the container
MessageBox This module is used to display the message-box in the desktop based applications.

 Python Tkinter Geometry

The Tkinter geometry specifies the method by using which, the widgets are represented on display. The
python Tkinter provides the following geometry methods.

Dr. Yusuf Perwej


 The pack() method
 The grid() method
 The place() method

 Python Tkinter pack() method

The pack() widget is used to organize widget in the block. The positions widgets added to the python
application using the pack() method can be controlled by using the various options specified in the
method call.
However, the controls are less and widgets are generally added in the less organized manner.
The syntax to use the pack() is given below.

Syntax
widget.pack(options)

A list of possible options that can be passed in pack() is given below.


 expand: If the expand is set to true, the widget expands to fill any space.
 Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine whether
the widget contains any extra space.
 size: it represents the side of the parent to which the widget is to be placed on the window.

Example:
# !/usr/bin/python3
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = “Red”, fg = “red”)
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = “Black”, fg = “black”)
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = “Blue”, fg = “blue”)
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = “Green”, fg = “red”)
blackbutton.pack( side = BOTTOM)
parent.mainloop()

Output:

 Python Tkinter grid() method

The grid() geometry manager organizes the widgets in the tabular form. We can specify the rows and
columns as the options in the method call. We can also specify the column span (width) or
rowspan(height) of a widget.
This is a more organized way to place the widgets to the python application. The syntax to use the grid()
is given below.

Syntax
Dr. Yusuf Perwej
widget.grid(options)

A list of possible options that can be passed inside the grid() method is given below.
 Column
The column number in which the widget is to be placed. The leftmost column is represented by
0.
 Columnspan
The width of the widget. It represents the number of columns up to which, the column is
expanded.
 ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
 padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
 row
The row number in which the widget is to be placed. The topmost row is represented by 0.
 rowspan
The height of the widget, i.e. the number of the row up to which the widget is expanded.
 Sticky
If the cell is larger than a widget, then sticky is used to specify the position of the widget inside
the cell. It may be the concatenation of the sticky letters representing the position of the widget.
It may be N, E, W, S, NE, NW, NS, EW, ES.

Example:
# !/usr/bin/python3
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()

Output:

 Python Tkinter place() method

The place() geometry manager organizes the widgets to the specific x and y coordinates.

Syntax
widget.place(options)

A list of possible options is given below.


 Anchor: It represents the exact position of the widget within the container. The default value
(direction) is NW (the upper left corner)

Dr. Yusuf Perwej


 bordermode: The default value of the border type is INSIDE that refers to ignore the parent's
inside the border. The other option is OUTSIDE.
 height, width: It refers to the height and width in pixels.
 relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the fraction of
the parent's height and width.
 relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the horizontal and
vertical direction.
 x, y: It refers to the horizontal and vertical offset in the pixels.

Example:
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()

Output:

 Python Tkinter Button

The button widget is used to add various types of buttons to the python application. Python allows us to
configure the look of the button according to our requirements. Various options can be set or reset
depending upon the requirements.
We can also associate a method or function with a button which is called when the button is pressed.
The syntax to use the button widget is given below.

Syntax
W = Button(parent, options)

A list of possible options is given below.

Option Description
activebackground It represents the background of the button when the mouse hover the button.
activeforeground It represents the font color of the button when the mouse hover the button.
Bd It represents the border width in pixels.
Bg It represents the background color of the button.
Dr. Yusuf Perwej
Command It is set to the function call which is scheduled when the function is called.
Fg Foreground color of the button.
Font The font of the button text.
The height of the button. The height is represented in the number of text lines for
Height
the textual lines or the number of pixels for the images.
Highlightcolor The color of the highlight when the button has the focus.
Image It is set to the image displayed on the button.
It illustrates the way by which the multiple text lines are represented. It is set to
justify LEFT for left justification, RIGHT for the right justification, and CENTER for the
center.
Padx Additional padding to the button in the horizontal direction.
pady Additional padding to the button in the vertical direction.
It represents the type of the border. It can be SUNKEN, RAISED, GROOVE, and
Relief
RIDGE.
This option is set to DISABLED to make the button unresponsive. The ACTIVE
State
represents the active state of the button.
Underline Set this option to make the button text underlined.
The width of the button. It exists as a number of letters for textual buttons or pixels
Width
for image buttons.
If the value is set to a positive number, the text lines will be wrapped to fit within
Wraplength
this length.
Example:
#python application to create a simple button

from tkinter import *

top = Tk()

top.geometry("200x100")

b = Button(top,text = "Simple")

b.pack()

top.mainaloop()

Output:

Example:
from tkinter import *

top = Tk()

Dr. Yusuf Perwej


top.geometry("200x100")

def fun():
messagebox.showinfo("Hello", "Red Button clicked")

b1 = Button(top,text = "Red",command = fun,activeforeground = "red",activebackground = "pink",pady


=10)

b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=10)

b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink",pady = 10)

b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",pady = 10)

b1.pack(side = LEFT)

b2.pack(side = RIGHT)

b3.pack(side = TOP)

b4.pack(side = BOTTOM)

top.mainloop()

Output:

 Python Tkinter Canvas

The canvas widget is used to add the structured graphics to the python application. It is used to draw the
graph and plots to the python application. The syntax to use the canvas is given below.

Syntax
w = canvas(parent, options)
A list of possible options is given below.

Option Description
bd The represents the border width. The default width is 2.
bg It represents the background color of the canvas.

Dr. Yusuf Perwej


confine It is set to make the canvas unscrollable outside the scroll region.
cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.
height It represents the size of the canvas in the vertical direction.
highlightcolor It represents the highlight color when the widget is focused.
It represents the type of the border. The possible values are SUNKEN, RAISED,
relief
GROOVE, and RIDGE.
scrollregion It represents the coordinates specified as the tuple containing the area of the canvas.
width It represents the width of the canvas.
xscrollincrement If it is set to a positive value. The canvas is placed only to the multiple of this value.
If the canvas is scrollable, this attribute should be the .set() method of the horizontal
xscrollcommand
scrollbar.
yscrollincrement Works like xscrollincrement, but governs vertical movement.
If the canvas is scrollable, this attribute should be the .set() method of the vertical
yscrollcommand
scrollbar.
Example:
from tkinter import *

top = Tk()

top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200")

c.pack()

top.mainloop()
Output:

Example: Creating an arc


from tkinter import *

top = Tk()

top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200",width = 200)

arc = c.create_arc((5,10,150,200),start = 0,extent = 150, fill= "white")

c.pack()
Dr. Yusuf Perwej
top.mainloop()

Output:

 Python Tkinter Canvas

The canvas widget is used to add the structured graphics to the python application. It is used to draw the
graph and plots to the python application. The syntax to use the canvas is given below.

Syntax
w = canvas(parent, options)

A list of possible options is given below.

Option Description
bd The represents the border width. The default width is 2.
bg It represents the background color of the canvas.
confine It is set to make the canvas unscrollable outside the scroll region.
cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.
height It represents the size of the canvas in the vertical direction.
highlightcolor It represents the highlight color when the widget is focused.
It represents the type of the border. The possible values are SUNKEN, RAISED,
relief
GROOVE, and RIDGE.
scrollregion It represents the coordinates specified as the tuple containing the area of the canvas.
width It represents the width of the canvas.
xscrollincrement If it is set to a positive value. The canvas is placed only to the multiple of this value.
If the canvas is scrollable, this attribute should be the .set() method of the horizontal
xscrollcommand
scrollbar.
yscrollincrement Works like xscrollincrement, but governs vertical movement.
If the canvas is scrollable, this attribute should be the .set() method of the vertical
yscrollcommand
scrollbar.
Example
from tkinter import *

top = Tk()

top.geometry("200x200")

Dr. Yusuf Perwej


#creating a simple canvas
c = Canvas(top,bg = "pink",height = "200")

c.pack()

top.mainloop()

Output:

Example: Creating an arc


from tkinter import *

top = Tk()

top.geometry("200x200")

#creating a simple canvas


c = Canvas(top,bg = "pink",height = "200",width = 200)

arc = c.create_arc((5,10,150,200),start = 0,extent = 150, fill= "white")

c.pack()

top.mainloop()

Output:

 Python Tkinter Entry

The Entry widget is used to provde the single line text-box to the user to accept a value from the user.
We can use the Entry widget to accept the text strings from the user. It can only be used for one line of
text from the user. For multiple lines of text, we must use the text widget.
Dr. Yusuf Perwej
The syntax to use the Entry widget is given below.

Syntax
w = Entry (parent, options)

A list of possible options is given below.

Option Description
bg The background color of the widget.
bd The border width of the widget in pixels.
cursor The mouse pointer will be changed to the cursor type set to the arrow, dot, etc.
The text written inside the entry box will be automatically copied to the
exportselection
clipboard by default. We can set the exportselection to 0 to not copy this.
fg It represents the color of the text.
font It represents the font type of the text.
It represents the color to display in the traversal highlight region when the
highlightbackground
widget does not have the input focus.
It represents the color to use for the traversal highlight rectangle that is drawn
highlightcolor
around the widget when it has the input focus.
It represents a non-negative value indicating the width of the highlight
highlightthickness
rectangle to draw around the outside of the widget when it has the input focus.
It represents the color to use as background in the area covered by the insertion
insertbackground cursor. This color will normally override either the normal background for the
widget.
It represents a non-negative value indicating the width of the 3-D border to
insertborderwidth draw around the insertion cursor. The value may have any of the forms
acceptable to Tk_GetPixels.
It represents a non-negative integer value indicating the number of milliseconds
insertofftime the insertion cursor should remain "off" in each blink cycle. If this option is
zero, then the cursor doesn't blink: it is on all the time.
Specifies a non-negative integer value indicating the number of milliseconds
insertontime
the insertion cursor should remain "on" in each blink cycle.
It represents the value indicating the total width of the insertion cursor. The
insertwidth
value may have any of the forms acceptable to Tk_GetPixels.
justify It specifies how the text is organized if the text contains multiple lines.
relief It specifies the type of the border. Its default value is FLAT.
selectbackground The background color of the selected text.
selectborderwidth The width of the border to display around the selected task.
selectforeground The font color of the selected task.
It is used to show the entry text of some other type instead of the string. For
show
example, the password is typed using stars (*).
textvariable It is set to the instance of the StringVar to retrieve the text from the entry.
width The width of the displayed text or image.
The entry widget can be linked to the horizontal scrollbar if we want the user to
xscrollcommand
enter more text then the actual width of the widget.
Example:
# !/usr/bin/python3
Dr. Yusuf Perwej
from tkinter import *

top = Tk()

top.geometry("400x250")

name = Label(top, text = "Name").place(x = 30,y = 50)

email = Label(top, text = "Email").place(x = 30, y = 90)

password = Label(top, text = "Password").place(x = 30, y = 130)

sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place


(x = 30, y = 170)

e1 = Entry(top).place(x = 80, y = 50)

e2 = Entry(top).place(x = 80, y = 90)

e3 = Entry(top).place(x = 95, y = 130)

top.mainloop()

Output:

 Entry widget methods

Python provides various methods to configure the data written inside the widget. There are the
following methods provided by the Entry widget.

Method Description
delete(first, last = none) It is used to delete the specified characters inside the widget.
get() It is used to get the text written inside the widget.
It is used to change the insertion cursor position. We can specify the
icursor(index)
index of the character before which, the cursor to be placed.
It is used to place the cursor to the left of the character written at the
index(index)
specified index.

Dr. Yusuf Perwej


It is used to insert the specified string before the character placed at the
insert(index,s)
specified index.
select_adjust(index) It includes the selection of the character present at the specified index.
select_clear() It clears the selection if some selection has been done.
select_form(index) It sets the anchor index position to the character specified by the index.
select_present() It returns true if some text in the Entry is selected otherwise returns false.
select_range(start,end) It selects the characters to exist between the specified range.
select_to(index) It selects all the characters from the beginning to the specified index.
xview(index) It is used to link the entry widget to a horizontal scrollbar.
xview_scroll(number,what) It is used to make the entry scrollable horizontally.

Example: A simple calculator


import tkinter as tk
from functools import partial

def call_result(label_result, n1, n2):


num1 = (n1.get())
num2 = (n2.get())
result = int(num1)+int(num2)
label_result.config(text="Result = %d" % result)
return

root = tk.Tk()
root.geometry('400x200+100+200')

root.title('Calculator')

number1 = tk.StringVar()
number2 = tk.StringVar()

labelNum1 = tk.Label(root, text="A").grid(row=1, column=0)

labelNum2 = tk.Label(root, text="B").grid(row=2, column=0)

labelResult = tk.Label(root)

labelResult.grid(row=7, column=2)

entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)

entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)

call_result = partial(call_result, labelResult, number1, number2)

buttonCal = tk.Button(root, text="Calculate", command=call_result).grid(row=3, column=0)

root.mainloop()

Output:

Dr. Yusuf Perwej


 Python Tkinter Entry

The Entry widget is used to provde the single line text-box to the user to accept a value from the user.
We can use the Entry widget to accept the text strings from the user. It can only be used for one line of
text from the user. For multiple lines of text, we must use the text widget.
The syntax to use the Entry widget is given below.

Syntax
w = Entry (parent, options)

A list of possible options is given below.

Option Description
bg The background color of the widget.
bd The border width of the widget in pixels.
cursor The mouse pointer will be changed to the cursor type set to the arrow, dot, etc.
The text written inside the entry box will be automatically copied to the
exportselection
clipboard by default. We can set the exportselection to 0 to not copy this.
fg It represents the color of the text.
font It represents the font type of the text.
It represents the color to display in the traversal highlight region when the
highlightbackground
widget does not have the input focus.
It represents the color to use for the traversal highlight rectangle that is drawn
highlightcolor
around the widget when it has the input focus.
It represents a non-negative value indicating the width of the highlight
highlightthickness
rectangle to draw around the outside of the widget when it has the input focus.
It represents the color to use as background in the area covered by the insertion
insertbackground cursor. This color will normally override either the normal background for the
widget.
It represents a non-negative value indicating the width of the 3-D border to
insertborderwidth draw around the insertion cursor. The value may have any of the forms
acceptable to Tk_GetPixels.
It represents a non-negative integer value indicating the number of milliseconds
insertofftime the insertion cursor should remain "off" in each blink cycle. If this option is
zero, then the cursor doesn't blink: it is on all the time.
Specifies a non-negative integer value indicating the number of milliseconds
insertontime
the insertion cursor should remain "on" in each blink cycle.

Dr. Yusuf Perwej


It represents the value indicating the total width of the insertion cursor. The
insertwidth
value may have any of the forms acceptable to Tk_GetPixels.
justify It specifies how the text is organized if the text contains multiple lines.
relief It specifies the type of the border. Its default value is FLAT.
selectbackground The background color of the selected text.
selectborderwidth The width of the border to display around the selected task.
selectforeground The font color of the selected task.
It is used to show the entry text of some other type instead of the string. For
show
example, the password is typed using stars (*).
textvariable It is set to the instance of the StringVar to retrieve the text from the entry.
width The width of the displayed text or image.
The entry widget can be linked to the horizontal scrollbar if we want the user to
xscrollcommand
enter more text then the actual width of the widget.
Example
# !/usr/bin/python3

from tkinter import *

top = Tk()

top.geometry("400x250")

name = Label(top, text = "Name").place(x = 30,y = 50)

email = Label(top, text = "Email").place(x = 30, y = 90)

password = Label(top, text = "Password").place(x = 30, y = 130)

sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place(x


= 30, y = 170)

e1 = Entry(top).place(x = 80, y = 50)

e2 = Entry(top).place(x = 80, y = 90)

e3 = Entry(top).place(x = 95, y = 130)

top.mainloop()

Output:

Dr. Yusuf Perwej


 Entry widget methods

Python provides various methods to configure the data written inside the widget. There are the
following methods provided by the Entry widget.

Method Description
delete(first, last = none)It is used to delete the specified characters inside the widget.
get() It is used to get the text written inside the widget.
It is used to change the insertion cursor position. We can specify the
icursor(index)
index of the character before which, the cursor to be placed.
It is used to place the cursor to the left of the character written at the
index(index)
specified index.
It is used to insert the specified string before the character placed at the
insert(index,s)
specified index.
select_adjust(index) It includes the selection of the character present at the specified index.
select_clear() It clears the selection if some selection has been done.
select_form(index) It sets the anchor index position to the character specified by the index.
select_present() It returns true if some text in the Entry is selected otherwise returns false.
select_range(start,end) It selects the characters to exist between the specified range.
select_to(index) It selects all the characters from the beginning to the specified index.
xview(index) It is used to link the entry widget to a horizontal scrollbar.
xview_scroll(number,what) It is used to make the entry scrollable horizontally.

Example: A simple calculator


import tkinter as tk
from functools import partial

def call_result(label_result, n1, n2):


num1 = (n1.get())
num2 = (n2.get())
result = int(num1)+int(num2)
label_result.config(text="Result = %d" % result)
return

root = tk.Tk()
root.geometry('400x200+100+200')

Dr. Yusuf Perwej


root.title('Calculator')

number1 = tk.StringVar()
number2 = tk.StringVar()

labelNum1 = tk.Label(root, text="A").grid(row=1, column=0)

labelNum2 = tk.Label(root, text="B").grid(row=2, column=0)

labelResult = tk.Label(root)

labelResult.grid(row=7, column=2)

entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)

entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)

call_result = partial(call_result, labelResult, number1, number2)

buttonCal = tk.Button(root, text="Calculate", command=call_result).grid(row=3, column=0)

root.mainloop()

Output:

 Python Tkinter Label

The Label is used to specify the container box where we can place the text or images. This widget is
used to provide the message to the user about other widgets used in the python application.

There are the various options which can be specified to configure the text or the part of the text shown in
the Label.

Syntax
w = Label (master, options)

A list of possible options is given below.

Dr. Yusuf Perwej


Option Description
It specifies the exact position of the text within the size provided to the widget. The
anchor
default value is CENTER, which is used to center the text within the specified space.
bg The background color displayed behind the widget.
It is used to set the bitmap to the graphical object specified so that, the label can represent
bitmap
the graphics instead of text.
bd It represents the width of the border. The default is 2 pixels.
The mouse pointer will be changed to the type of the cursor specified, i.e., arrow, dot,
cursor
etc.
font The font type of the text written inside the widget.
fg The foreground color of the text written inside the widget.
height The height of the widget.
image The image that is to be shown as the label.
It is used to represent the orientation of the text if the text contains multiple lines. It can
justify be set to LEFT for left justification, RIGHT for right justification, and CENTER for
center justification.
padx The horizontal padding of the text. The default value is 1.
pady The vertical padding of the text. The default value is 1.
relief The type of the border. The default value is FLAT.
text This is set to the string variable which may contain one or more line of text.
The text written inside the widget is set to the control variable StringVar so that it can be
textvariable
accessed and changed accordingly.
We can display a line under the specified letter of the text. Set this option to the number
underline
of the letter under which the line will be displayed.
width The width of the widget. It is specified as the number of characters.
Instead of having only one line as the label text, we can break it to the number of lines
wraplength
where each line has the number of characters specified to this option.
Example:
# !/usr/bin/python3

from tkinter import *

top = Tk()

top.geometry("400x250")

#creating label
uname = Label(top, text = "Username").place(x = 30,y = 50)

#creating label
password = Label(top, text = "Password").place(x = 30, y = 90)

sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place(x


= 30, y = 120)

e1 = Entry(top,width = 20).place(x = 100, y = 50)

Dr. Yusuf Perwej


e2 = Entry(top, width = 20).place(x = 100, y = 90)

top.mainloop()

Output:

 Python Tkinter Listbox

The Listbox widget is used to display the list items to the user. We can place only text items in the
Listbox and all text items contain the same font and color.

The user can choose one or more items from the list depending upon the configuration.
The syntax to use the Listbox is given below.

w = Listbox(parent, options)

A list of possible options is given below.

Option Description
bg The background color of the widget.
bd It represents the size of the border. Default value is 2 pixel.
cursor The mouse pointer will look like the cursor type like dot, arrow, etc.
font The font type of the Listbox items.
fg The color of the text.
height It represents the count of the lines shown in the Listbox. The default value is 10.
highlightcolor The color of the Listbox items when the widget is under focus.
highlightthickness The thickness of the highlight.
relief The type of the border. The default is SUNKEN.
selectbackground The background color that is used to display the selected text.
It is used to determine the number of items that can be selected from the list. It can
selectmode
set to BROWSE, SINGLE, MULTIPLE, EXTENDED.
width It represents the width of the widget in characters.
xscrollcommand It is used to let the user scroll the Listbox horizontally.
yscrollcommand It is used to let the user scroll the Listbox vertically.

Dr. Yusuf Perwej


 Methods

There are the following methods associated with the Listbox.

Method Description
activate(index) It is used to select the lines at the specified index.
It returns a tuple containing the line numbers of the selected element or
curselection()
elements, counting from 0. If nothing is selected, returns an empty tuple.
delete(first, last = None) It is used to delete the lines which exist in the given range.
get(first, last = None) It is used to get the list items that exist in the given range.
index(i) It is used to place the line with the specified index at the top of the widget.
It is used to insert the new lines with the specified number of elements
insert(index, *elements)
before the specified index.
It returns the index of the nearest line to the y coordinate of the Listbox
nearest(y)
widget.
It is used to adjust the position of the listbox to make the lines specified by
see(index)
the index visible.
size() It returns the number of lines that are present in the Listbox widget.
xview() This is used to make the widget horizontally scrollable.
It is used to make the listbox horizontally scrollable by the fraction of
xview_moveto(fraction)
width of the longest line present in the listbox.
xview_scroll(number, It is used to make the listbox horizontally scrollable by the number of
what) characters specified.
yview() It allows the Listbox to be vertically scrollable.
It is used to make the listbox vertically scrollable by the fraction of width
yview_moveto(fraction)
of the longest line present in the listbox.
yview_scroll (number, It is used to make the listbox vertically scrollable by the number of
what) characters specified.

Example:
# !/usr/bin/python3

from tkinter import *

top = Tk()

top.geometry("200x250")

lbl = Label(top,text = "A list of favourite countries...")

listbox = Listbox(top)

listbox.insert(1,"India")

listbox.insert(2, "USA")

listbox.insert(3, "Japan")

Dr. Yusuf Perwej


listbox.insert(4, "Austrelia")

lbl.pack()
listbox.pack()

top.mainloop()

Output:

Example: Deleting the active items from the list


# !/usr/bin/python3

from tkinter import *

top = Tk()

top.geometry("200x250")

lbl = Label(top,text = "A list of favourite countries...")

listbox = Listbox(top)

listbox.insert(1,"India")

listbox.insert(2, "USA")

listbox.insert(3, "Japan")

listbox.insert(4, "Austrelia")

#this button will delete the selected item from the list

btn = Button(top, text = "delete", command = lambda listbox=listbox: listbox.delete(ANCHOR))

lbl.pack()

Dr. Yusuf Perwej


listbox.pack()

btn.pack()
top.mainloop()

Output:

After pressing the delete button.

 Python Tkinter Menubutton

The Menubutton widget can be defined as the drop-down menu that is shown to the user all the time. It
is used to provide the user a option to select the appropriate choice exist within the application.

The Menubutton is used to implement various types of menus in the python application. A Menu is
associated with the Menubutton that can display the choices of the Menubutton when clicked by the
user.

The syntax to use the python tkinter Menubutton is given below.

Syntax
w = Menubutton(Top, options)

Dr. Yusuf Perwej


A list of various options is given below.

Option Description
activebackground The background color of the widget when the widget is under focus.
activeforeground The font color of the widget text when the widget is under focus.
It specifies the exact position of the widget content when the widget is assigned
anchor
more space than needed.
bg It specifies the background color of the widget.
bitmap It is set to the graphical content which is to be displayed to the widget.
bd It represents the size of the border. The default value is 2 pixels.
The mouse pointer will be changed to the cursor type specified when the widget
cursor
is under the focus. The possible value of the cursor type is arrow, or dot etc.
It direction can be specified so that menu can be displayed to the specified
direction direction of the button. Use LEFT, RIGHT, or ABOVE to place the widget
accordingly.
disabledforeground The text color of the widget when the widget is disabled.
fg The normal foreground color of the widget.
height The vertical dimension of the Menubutton. It is specified as the number of lines.
highlightcolor The highlight color shown to the widget under focus.
image The image displayed on the widget.
This specified the exact position of the text under the widget when the text is
unable to fill the width of the widget. We can use the LEFT for the left
justify
justification, RIGHT for the right justification, CENTER for the centre
justification.
menu It represents the menu specified with the Menubutton.
padx The horizontal padding of the widget.
pady The vertical padding of the widget.
relief This option specifies the type of the border. The default value is RAISED.
The normal state of the Mousebutton is enabled. We can set it to DISABLED to
state
make it unresponsive.
text The text shown with the widget.
We can set the control variable of string type to the text variable so that we can
textvariable
control the text of the widget at runtime.
The text of the widget is not underlined by default but we can set this option to
underline
make the text of the widget underlined.
width It represents the width of the widget in characters. The default value is 20.
We can break the text of the widget in the number of lines so that the text
wraplength
contains the number of lines not greater than the specified value.

Example:
# !/usr/bin/python3

from tkinter import *

top = Tk()

Dr. Yusuf Perwej


top.geometry("200x250")

menubutton = Menubutton(top, text = "Language", relief = FLAT)

menubutton.grid()

menubutton.menu = Menu(menubutton)

menubutton["menu"]=menubutton.menu

menubutton.menu.add_checkbutton(label = "Hindi", variable=IntVar())

menubutton.menu.add_checkbutton(label = "English", variable = IntVar())

menubutton.pack()

top.mainloop()

Output:

 Python Tkinter Menu

The Menu widget is used to create various types of menus (top level, pull down, and pop up) in the
python application.

The top-level menus are the one which is displayed just under the title bar of the parent window. We
need to create a new instance of the Menu widget and add various commands to it by using the add()
method.

The syntax to use the Menu widget is given below.

Syntax
w = Menu(top, options)
A list of possible options is given below.

Option Description
activebackground The background color of the widget when the widget is under the focus.

Dr. Yusuf Perwej


The width of the border of the widget when it is under the mouse. The default is
activeborderwidth
1 pixel.
activeforeground The font color of the widget when the widget has the focus.
bg The background color of the widget.
bd The border width of the widget.
The mouse pointer is changed to the cursor type when it hovers the widget. The
cursor
cursor type can be set to arrow or dot.
disabledforeground The font color of the widget when it is disabled.
font The font type of the text of the widget.
fg The foreground color of the widget.
The postcommand can be set to any of the function which is called when the
postcommand
mourse hovers the menu.
relief The type of the border of the widget. The default type is RAISED.
image It is used to display an image on the menu.
selectcolor The color used to display the checkbutton or radiobutton when they are selected.
By default, the choices in the menu start taking place from position 1. If we set
tearoff
the tearoff = 1, then it will start taking place from 0th position.
Set this option to the title of the window if you want to change the title of the
title
window.
 Methods

The Menu widget contains the following methods.

Option Description
add_command(options) It is used to add the Menu items to the menu.
add_radiobutton(options) This method adds the radiobutton to the menu.
add_checkbutton(options) This method is used to add the checkbuttons to the menu.
It is used to create a hierarchical menu to the parent menu by associating
add_cascade(options)
the given menu to the parent menu.
add_seperator() It is used to add the seperator line to the menu.
add(type, options) It is used to add the specific menu item to the menu.
delete(startindex,
It is used to delete the menu items exist in the specified range.
endindex)
entryconfig(index, options) It is used to configure a menu item identified by the given index.
index(item) It is used to get the index of the specified menu item.
insert_seperator(index) It is used to insert a seperator at the specified index.
It is used to invoke the associated with the choice given at the specified
invoke(index)
index.
type(index) It is used to get the type of the choice specified by the index.
 Creating a top level menu

A top-level menu can be created by instantiating the Menu widget and adding the menu items to the
menu.

Example:
# !/usr/bin/python3

Dr. Yusuf Perwej


from tkinter import *

top = Tk()

def hello():
print("hello!")

# create a toplevel menu


menubar = Menu(root)
menubar.add_command(label="Hello!", command=hello)
menubar.add_command(label="Quit!", command=top.quit)

# display the menu


top.config(menu=menubar)

top.mainloop()

Output:

Clicking the hello Menubutton will print the hello on the console while clicking the Quit Menubutton
will make an exit from the python application.

Example:
from tkinter import Toplevel, Button, Tk, Menu

top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")

file.add_separator()

file.add_command(label="Exit", command=top.quit)

menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
Dr. Yusuf Perwej
edit.add_command(label="Undo")

edit.add_separator()

edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")

menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)

top.config(menu=menubar)
top.mainloop()

Output:

 Python Tkinter Message

The Message widget is used to show the message to the user regarding the behaviour of the python
application. The message widget shows the text messages to the user which can not be edited.

The message text contains more than one line. However, the message can only be shown in the single
font.

The syntax to use the Message widget is given below.

Syntax
w = Message(parent, options)
A list of possible options is given below.

Option Description
It is used to decide the exact position of the text within the space provided to the widget
anchor
if the widget contains more space than the need of the text. The default is CENTER.
bg The background color of the widget.
Dr. Yusuf Perwej
It is used to display the graphics on the widget. It can be set to any graphical or image
bitmap
object.
bd It represents the size of the border in the pixel. The default size is 2 pixel.
The mouse pointer is changed to the specified cursor type. The cursor type can be an
cursor
arrow, dot, etc.
font The font type of the widget text.
fg The font color of the widget text.
height The vertical dimension of the message.
image We can set this option to a static image to show that onto the widget.
This option is used to specify the alignment of multiple line of code with respect to each
justify other. The possible values can be LEFT (left alignment), CENTER (default), and RIGHT
(right alignment).
padx The horizontal padding of the widget.
pady The vertical padding of the widget.
relief It represents the type of the border. The default type is FLAT.
text We can set this option to the string so that the widget can represent the specified text.
This is used to control the text represented by the widget. The textvariable can be set to
textvariable
the text that is shown in the widget.
The default value of this option is -1 that represents no underline. We can set this option
underline
to an existing number to specify that nth letter of the string will be underlined.
It specifies the horizontal dimension of the widget in the number of characters (not
width
pixel).
We can wrap the text to the number of lines by setting this option to the desired number
wraplength
so that each line contains only that number of characters.
Example:
from tkinter import *

top = Tk()
top.geometry("100x100")
var = StringVar()
msg = Message( top, text = "Welcome to GITM")

msg.pack()
top.mainloop()

Output:

 Python Tkinter Radiobutton

Dr. Yusuf Perwej


The Radiobutton widget is used to implement one-of-many selection in the python application. It shows
multiple choices to the user out of which, the user can select only one out of them. We can associate
different methods with each of the radiobutton.

We can display the multiple line text or images on the radiobuttons. To keep track the user's selection
the radiobutton, it is associated with a single variable. Each button displays a single value for that
particular variable.

The syntax to use the Radiobutton is given below.

Syntax
w = Radiobutton(top, options)

Option Description
activebackground The background color of the widget when it has the focus.
activeforeground The font color of the widget text when it has the focus.
It represents the exact position of the text within the widget if the widget
anchor contains more space than the requirement of the text. The default value is
CENTER.
bg The background color of the widget.
It is used to display the graphics on the widget. It can be set to any graphical or
bitmap
image object.
borderwidth It represents the size of the border.
This option is set to the procedure which must be called every-time when the
command
state of the radiobutton is changed.
The mouse pointer is changed to the specified cursor type. It can be set to the
cursor
arrow, dot, etc.
font It represents the font type of the widget text.
fg The normal foreground color of the widget text.
The vertical dimension of the widget. It is specified as the number of lines (not
height
pixel).
highlightcolor It represents the color of the focus highlight when the widget has the focus.
highlightbackground The color of the focus highlight when the widget is not having the focus.
It can be set to an image object if we want to display an image on the
image
radiobutton instead the text.
It represents the justification of the multi-line text. It can be set to
justify
CENTER(default), LEFT, or RIGHT.
padx The horizontal padding of the widget.
pady The vertical padding of the widget.
relief The type of the border. The default value is FLAT.
selectcolor The color of the radio button when it is selected.
selectimage The image to be displayed on the radiobutton when it is selected.
It represents the state of the radio button. The default state of the Radiobutton is
state NORMAL. However, we can set this to DISABLED to make the radiobutton
unresponsive.
text The text to be displayed on the radiobutton.
textvariable It is of String type that represents the text displayed by the widget.
Dr. Yusuf Perwej
The default value of this option is -1, however, we can set this option to the
underline
number of character which is to be underlined.
The value of each radiobutton is assigned to the control variable when it is
value
turned on by the user.
It is the control variable which is used to keep track of the user's choices. It is
variable
shared among all the radiobuttons.
The horizontal dimension of the widget. It is represented as the number of
width
characters.
We can wrap the text to the number of lines by setting this option to the desired
wraplength
number so that each line contains only that number of characters.
 Methods

The radiobutton widget provides the following methods.

Method Description
deselect() It is used to turn of the radiobutton.
flash() It is used to flash the radiobutton between its active and normal colors few times.
invoke() It is used to call any procedure associated when the state of a Radiobutton is changed.
select() It is used to select the radiobutton.

Example:
from tkinter import *

def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)

top = Tk()
top.geometry("300x150")
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,
command=selection)
R1.pack( anchor = W )

R2 = Radiobutton(top, text="C++", variable=radio, value=2,


command=selection)
R2.pack( anchor = W )

R3 = Radiobutton(top, text="Java", variable=radio, value=3,


command=selection)
R3.pack( anchor = W)

label = Label(top)
label.pack()
top.mainloop()

Output:

Dr. Yusuf Perwej


 Python Tkinter Scale

The Scale widget is used to implement the graphical slider to the python application so that the user can
slide through the range of values shown on the slider and select the one among them.

We can control the minimum and maximum values along with the resolution of the scale. It provides an
alternative to the Entry widget when the user is forced to select only one value from the given range of
values.
T
he syntax to use the Scale widget is given below.

Syntax
w = Scale(top, options)

A list of possible options is given below.

Option Description
activebackground The background color of the widget when it has the focus.
bg The background color of the widget.
bd The border size of the widget. The default is 2 pixel.
It is set to the procedure which is called each time when we move the slider. If
command
the slider is moved rapidly, the callback is done when it settles.
The mouse pointer is changed to the cursor type assigned to this option. It can
cursor
be an arrow, dot, etc.
If the control variable used to control the scale data is of string type, this option
digits is used to specify the number of digits when the numeric scale is converted to a
string.
font The font type of the widget text.
fg The foreground color of the text.
from_ It is used to represent one end of the widget range.
highlightbackground The highlight color when the widget doesn't have the focus.
highlighcolor The highlight color when the widget has the focus.
This can be set to some text which can be shown as a label with the scale. It is
label shown in the top left corner if the scale is horizontal or the top right corner if
the scale is vertical.
It represents the length of the widget. It represents the X dimension if the scale
length
is horizontal or y dimension if the scale is vertical.
orient It can be set to horizontal or vertical depending upon the type of the scale.

Dr. Yusuf Perwej


relief It represents the type of the border. The default is FLAT.
This option tells the duration up to which the button is to be pressed before the
repeatdelay
slider starts moving in that direction repeatedly. The default is 300 ms.
resolution It is set to the smallest change which is to be made to the scale value.
The value of the scale is shown in the text form by default. We can set this
showvalue
option to 0 to suppress the label.
It represents the length of the slider window along the length of the scale. The
sliderlength
default is 30 pixels. However, we can change it to the appropriate value.
The scale widget is active by default. We can set this to DISABLED to make it
state
unresponsive.
The focus cycles through the scale widgets by default. We can set this option to
takefocus
0 if we don't want this to happen.
The scale values are displayed on the multiple of the specified tick interval. The
tickinterval
default value of the tickinterval is 0.
It represents a float or integer value that specifies the other end of the range
to
represented by the scale.
troughcolor It represents the color of the through.
variable It represents the control variable for the scale.
width It represents the width of the through part of the widget.

 Methods
Method Description
get() It is used to get the current value of the scale.
set(value) It is used to set the value of the scale.

Example:
from tkinter import *

def select():
sel = "Value = " + str(v.get())
label.config(text = sel)

top = Tk()
top.geometry("200x100")
v = DoubleVar()
scale = Scale( top, variable = v, from_ = 1, to = 50, orient = HORIZONTAL)
scale.pack(anchor=CENTER)

btn = Button(top, text="Value", command=select)


btn.pack(anchor=CENTER)

label = Label(top)
label.pack()

top.mainloop()

Output:

Dr. Yusuf Perwej


 Python Tkinter Scrollbar

The scrollbar widget is used to scroll down the content of the other widgets like listbox, text, and
canvas. However, we can also create the horizontal scrollbars to the Entry widget.
The syntax to use the Scrollbar widget is given below.

Syntax
w = Scrollbar(top, options)

A list of possible options is given below.

Option Description
activebackground The background color of the widget when it has the focus.
bg The background color of the widget.
bd The border width of the widget.
It can be set to the procedure associated with the list which can be called each
command
time when the scrollbar is moved.
The mouse pointer is changed to the cursor type set to this option which can be
cursor
an arrow, dot, etc.
It represents the border width around the arrow heads and slider. The default
elementborderwidth
value is -1.
Highlightbackground The focus highlighcolor when the widget doesn't have the focus.
highlighcolor The focus highlighcolor when the widget has the focus.
highlightthickness It represents the thickness of the focus highlight.
It is used to control the behavior of the scroll jump. If it set to 1, then the
jump
callback is called when the user releases the mouse button.
It can be set to HORIZONTAL or VERTICAL depending upon the orientation
orient
of the scrollbar.
This option tells the duration up to which the button is to be pressed before the
repeatdelay
slider starts moving in that direction repeatedly. The default is 300 ms.
repeatinterval The default value of the repeat interval is 100.
We can tab the focus through this widget by default. We can set this option to
takefocus
0 if we don't want this behavior.
troughcolor It represents the color of the trough.
width It represents the width of the scrollbar.

 Methods

The widget provides the following methods.

Dr. Yusuf Perwej


Method Description
get() It returns the two numbers a and b which represents the current position of the scrollbar.
set(first, It is used to connect the scrollbar to the other widget w. The yscrollcommand or
last) xscrollcommand of the other widget to this method.

Example:
from tkinter import *

top = Tk()
sb = Scrollbar(top)
sb.pack(side = RIGHT, fill = Y)

mylist = Listbox(top, yscrollcommand = sb.set )

for line in range(30):


mylist.insert(END, "Number " + str(line))

mylist.pack( side = LEFT )


sb.config( command = mylist.yview )

mainloop()

Output:

 Python Tkinter Text

The Text widget is used to show the text data on the Python application. However, Tkinter provides us
the Entry widget which is used to implement the single line text box.

The Text widget is used to display the multi-line formatted text with various styles and attributes. The
Text widget is mostly used to provide the text editor to the user.

The Text widget also facilitates us to use the marks and tabs to locate the specific sections of the Text.
We can also use the windows and images with the Text as it can also be used to display the formatted
text.

The syntax to use the Text widget is given below.

Syntax
w = Text(top, options)

A list of possible options that can be used with the Text widget is given below.
Dr. Yusuf Perwej
Option Description
bg The background color of the widget.
bd It represents the border width of the widget.
cursor The mouse pointer is changed to the specified cursor type, i.e. arrow, dot, etc.
The selected text is exported to the selection in the window manager. We can
exportselection
set this to 0 if we don't want the text to be exported.
font The font type of the text.
fg The text color of the widget.
height The vertical dimension of the widget in lines.
highlightbackground The highlightcolor when the widget doesn't has the focus.
highlightthickness The thickness of the focus highlight. The default value is 1.
highlighcolor The color of the focus highlight when the widget has the focus.
insertbackground It represents the color of the insertion cursor.
insertborderwidth It represents the width of the border around the cursor. The default is 0.
The time amount in Milliseconds during which the insertion cursor is off in the
insertofftime
blink cycle.
The time amount in Milliseconds during which the insertion cursor is on in the
insertontime
blink cycle.
insertwidth It represents the width of the insertion cursor.
padx The horizontal padding of the widget.
pady The vertical padding of the widget.
relief The type of the border. The default is SUNKEN.
selectbackground The background color of the selected text.
selectborderwidth The width of the border around the selected text.
It specifies the amount of vertical space given above each line of the text. The
spacing1
default is 0.
This option specifies how much extra vertical space to add between displayed
spacing2
lines of text when a logical line wraps. The default is 0.
spacing3 It specifies the amount of vertical space to insert below each line of the text.
It the state is set to DISABLED, the widget becomes unresponsive to the mouse
state
and keyboard unresponsive.
tabs This option controls how the tab character is used to position the text.
width It represents the width of the widget in characters.
This option is used to wrap the wider lines into multiple lines. Set this option to
the WORD to wrap the lines after the word that fit into the available space. The
wrap
default value is CHAR which breaks the line which gets too wider at any
character.
To make the Text widget horizontally scrollable, we can set this option to the
xscrollcommand
set() method of Scrollbar widget.
To make the Text widget vertically scrollable, we can set this option to the set()
yscrollcommand
method of Scrollbar widget.

 Methods
We can use the following methods with the Text widget.

Dr. Yusuf Perwej


Method Description
delete(startindex,
This method is used to delete the characters of the specified range.
endindex)
get(startindex,
It returns the characters present in the specified range.
endindex)
index(index) It is used to get the absolute index of the specified index.
insert(index, string)
It is used to insert the specified string at the given index.
It returns a boolean value true or false depending upon whether the text at
see(index)
the specified index is visible or not.
 Mark handling methods

Marks are used to bookmark the specified position between the characters of the associated text.
Description
Method
index(mark) It is used to get the index of the specified mark.
mark_gravity(mark, gravity) It is used to get the gravity of the given mark.
mark_names() It is used to get all the marks present in the Text widget.
mark_set(mark, index) It is used to inform a new position of the given mark.
mark_unset(mark) It is used to remove the given mark from the text.

 Tag handling methods

The tags are the names given to the separate areas of the text. The tags are used to configure the
different areas of the text separately. The list of tag-handling methods along with the description is
given below.

Method Description
This method is used to tag the string present in the
tag_add(tagname, startindex, endindex)
specified range.
tag_config This method is used to configure the tag properties.
tag_delete(tagname) This method is used to delete a given tag.
tag_remove(tagname, startindex, This method is used to remove a tag from the specified
endindex) range.
Example:
from tkinter import *

top = Tk()
text = Text(top)
text.insert(INSERT, "Name.....")
text.insert(END, "Salary.....")

text.pack()

text.tag_add("Write Here", "1.0", "1.4")


text.tag_add("Click Here", "1.8", "1.13")

text.tag_config("Write Here", background="yellow", foreground="black")


text.tag_config("Click Here", background="black", foreground="white")

Dr. Yusuf Perwej


top.mainloop()
Output:

 Tkinter Toplevel

The Toplevel widget is used to create and display the toplevel windows which are directly managed by
the window manager. The toplevel widget may or may not have the parent window on the top of them.

The toplevel widget is used when a python application needs to represent some extra information, pop-
up, or the group of widgets on the new window.

The toplevel windows have the title bars, borders, and other window decorations.
The syntax to use the Toplevel widget is given below.

Syntax
w = Toplevel(options)

A List of possible options is given below.


Options Description
bg It represents the background color of the window.
bd It represents the border size of the window.
The mouse pointer is changed to the cursor type set to the arrow, dot, etc. when the mouse is
cursor
in the window.
The text selected in the text widget is exported to be selected to the window manager. We can
class_
set this to 0 to make this behavior false.
font The font type of the text inserted into the widget.
fg The foreground color of the widget.
height It represents the height of the window.
relief It represents the type of the window.
width It represents the width of the window,

 Methods

The methods associated with the Toplevel widget is given in the following list.

Method Description

Dr. Yusuf Perwej


deiconify() This method is used to display the window.
frame() It is used to show a system dependent window identifier.
group(window) It is used to add this window to the specified window group.
iconify() It is used to convert the toplevel window into an icon.
protocol(name,
It is used to mention a function which will be called for the specific protocol.
function)
It is used to get the current state of the window. Possible values are normal,
state()
iconic, withdrawn, and icon.
transient([master]) It is used to convert this window to a transient window (temporary).
withdraw() It is used to delete the window but doesn't destroy it.
maxsize(width, height) It is used to declare the maximum size for the window.
minsize(width, height) It is used to declare the minimum size for the window.
positionfrom(who) It is used to define the position controller.
resizable(width,
It is used to control whether the window can be resizable or not.
height)
sizefrom(who) It is used to define the size controller.
title(string) It is used to define the title for the window.

Example:
from tkinter import *

root = Tk()

root.geometry("200x200")

def open():
top = Toplevel(root)
top.mainloop()

btn = Button(root, text = "open", command = open)

btn.place(x=75,y=50)

root.mainloop()

Output:

 Python Tkinter Spinbox

Dr. Yusuf Perwej


The Spinbox widget is an alternative to the Entry widget. It provides the range of values to the user, out
of which, the user can select the one.

It is used in the case where a user is given some fixed number of values to choose from.
We can use various options with the Spinbox to decorate the widget. The syntax to use the Spinbox is
given below.

Syntax
w = Spinbox(top, options)

A list of possible options is given below.

Option Description
activebackground The background color of the widget when it has the focus.
bg The background color of the widget.
bd The border width of the widget.
The associated callback with the widget which is called each time the state of
command
the widget is called.
cursor The mouse pointer is changed to the cursor type assigned to this option.
disabledbackground The background color of the widget when it is disabled.
disabledforeground The foreground color of the widget when it is disabled.
fg The normal foreground color of the widget.
font The font type of the widget content.
format This option is used for the format string. It has no default value.
from_ It is used to show the starting range of the widget.
It is used to specify the justification of the multi-line widget content. The default
justify
is LEFT.
relief It is used to specify the type of the border. The default is SUNKEN.
This option is used to control the button auto repeat. The value is given in
repeatdelay
milliseconds.
repeatinterval It is similar to repeatdelay. The value is given in milliseconds.
It represents the state of the widget. The default is NORMAL. The possible
state
values are NORMAL, DISABLED, or "readonly".
It is like a control variable which is used to control the behaviour of the widget
textvariable
text.
It specify the maximum limit of the widget value. The other is specified by the
to
from_ option.
validate This option controls how the widget value is validated.
It is associated to the function callback which is used for the validation of the
validatecommand
widget content.
values It represents the tuple containing the values for this widget.
vcmd It is same as validation command.
width It represents the width of the widget.
wrap This option wraps up the up and down button the Spinbox.
This options is set to the set() method of scrollbar to make this widget
xscrollcommand
horizontally scrollable.

Dr. Yusuf Perwej


 Methods

There are the following methods associated with the widget.

Option Description
delete(startindex, This method is used to delete the characters present at the specified
endindex) range.
get(startindex, endindex) It is used to get the characters present in the specified range.
identify(x, y) It is used to identify the widget's element within the specified range.
index(index) It is used to get the absolute value of the given index.
insert(index, string) This method is used to insert the string at the specified index.
invoke(element) It is used to invoke the callback associated with the widget.

Example:
from tkinter import *

top = Tk()

top.geometry("200x200")

spin = Spinbox(top, from_= 0, to = 25)

spin.pack()

top.mainloop()

Output:

 Tkinter PanedWindow

The PanedWindow widget acts like a Container widget which contains one or more child widgets
(panes) arranged horizontally or vertically. The child panes can be resized by the user, by moving the
separator lines known as sashes by using the mouse.

Each pane contains only one widget. The PanedWindow is used to implement the different layouts in
the python applications.The syntax to use the PanedWindow is given below.

Syntax
w= PanedWindow(master, options)

A list of possible options is given below.

Dr. Yusuf Perwej


Option Description
bg It represents the background color of the widget when it doesn't have the focus.
It represents the 3D border size of the widget. The default option specifies that the
bd trough contains no border whereas the arrowheads and slider contain the 2-pixel border
size.
borderwidth It represents the border width of the widget. The default is 2 pixel.
cursor The mouse pointer is changed to the specified cursor type when it is over the window.
This option represents the distance between the handle and the end of the sash. For the
handlepad horizontal orientation, it is the distance between the top of the sash and the handle. The
default is 8 pixels.
It represents the size of the handle. The default size is 8 pixels. However, the handle will
handlesize
always be a square.
It represents the height of the widget. If we do not specify the height, it will be
height
calculated by the height of the child window.
relief It represents the type of the border. The default is FLAT.
sashpad It represents the padding to be done around each sash. The default is 0.
sashrelief
It represents the type of the border around each of the sash. The default is FLAT.
sashwidthIt represents the width of the sash. The default is 2 pixels.
showhandle
It is set to True to display the handles. The default value is false.
It represents the width of the widget. If we don't specify the width of the widget, it will
Width
be calculated by the size of the child widgets.
 Methods

There are the following methods that are associated with the PanedWindow.

Method Description
add(child, options) It is used to add a window to the parent window.
get(startindex, endindex) This method is used to get the text present at the specified range.
config(options) It is used to configure the widget with the specified options.

Example:
# !/usr/bin/python3
from tkinter import *

def add():
a = int(e1.get())
b = int(e2.get())
leftdata = str(a+b)
left.insert(1,leftdata)

w1 = PanedWindow()
w1.pack(fill = BOTH, expand = 1)

left = Entry(w1, bd = 5)
w1.add(left)

w2 = PanedWindow(w1, orient = VERTICAL)


w1.add(w2)
Dr. Yusuf Perwej
e1 = Entry(w2)
e2 = Entry(w2)

w2.add(e1)
w2.add(e2)

bottom = Button(w2, text = "Add", command = add)


w2.add(bottom)

mainloop()

Output:

 Tkinter LabelFrame

The LabelFrame widget is used to draw a border around its child widgets. We can also display the title
for the LabelFrame widget. It acts like a container which can be used to group the number of interrelated
widgets such as Radiobuttons.

This widget is a variant of the Frame widget which has all the features of a frame. It also can display a
label. The syntax to use the LabelFrame widget is given below.

Syntax
w = LabelFrame(top, options)

A list of options is given below.

Option Description
bg The background color of the widget.
It represents the size of the border shown around the indicator. The default is 2
bd
pixels.
Class The default value of the class is LabelFrame.
This option is used to specify which colomap is to be used for this widget. By
colormap colormap, we mean the 256 colors that are used to form the graphics. With this
option, we can reuse the colormap of another window on this widget.
If this is set to true, the LabelFrame becomes the container widget. The default
container
value is false.
It can be set to a cursor type, i.e. arrow, dot, etc. the mouse pointer is changed
cursor
to the cursor type when it is over the widget.
fg It represents the foreground color of the widget.
font It represents the font type of the widget text.
height It represents the height of the widget.

Dr. Yusuf Perwej


It represents the exact position of the text within the widget. The default is
labelAnchor
NW(north-west)
It represents the widget to be used for the label. The frame uses the text for the
labelwidget
label if no value specified.
highlightbackground The color of the focus highlight border when the widget doesn't have the focus.
highlightcolor The color of the focus highlight when the widget has the focus.
highlightthickness The width of the focus highlight border.
padx The horizontal padding of the widget.
pady The vertical padding of the widget.
relief It represents the border style. The default value is GROOVE.
text It represents the string containing the label text.
width It represents the width of the frame.

Example:
# !/usr/bin/python3
from tkinter import *

top = Tk()
top.geometry("300x200")

labelframe1 = LabelFrame(top, text="Positive Comments")


labelframe1.pack(fill="both", expand="yes")

toplabel = Label(labelframe1, text="Place to put the positive comments")


toplabel.pack()

labelframe2 = LabelFrame(top, text = "Negative Comments")


labelframe2.pack(fill="both", expand = "yes")

bottomlabel = Label(labelframe2,text = "Place to put the negative comments")


bottomlabel.pack()

top.mainloop()

Output:

 Tkinter messagebox

Dr. Yusuf Perwej


The messagebox module is used to display the message boxes in the python applications. There are the
various functions which are used to display the relevant messages depending upon the application
requirements.

The syntax to use the messagebox is given below.

Syntax
messagebox.function_name(title, message [, options])

Parameters
 function_name: It represents an appropriate message box function.
 title: It is a string which is shown as a title of a message box.
 message: It is the string to be displayed as a message on the message box.
 options: There are various options which can be used to configure the message dialog box.

The two options that can be used are default and parent.

1. default
A
The default option is used to mention the types of the default button, i.e. ABORT, RETRY, or
IGNORE in the message box.

2. parent

The parent option specifies the parent window on top of which, the message box is to be displayed.

There is one of the following functions used to show the appropriate message boxes. All the functions
are used with the same syntax but have the specific functionalities.

1. showinfo()

The showinfo() messagebox is used where we need to show some relevant information to the user.

Example:
# !/usr/bin/python3

from tkinter import *

from tkinter import messagebox

top = Tk()

top.geometry("100x100")

messagebox.showinfo("information","Information")

top.mainloop()

Output:

Dr. Yusuf Perwej


2. showwarning()

This method is used to display the warning to the user. Consider the following example.

Example:
# !/usr/bin/python3
from tkinter import *

from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.showwarning("warning","Warning")
top.mainloop()

Output:

3. showerror()

This method is used to display the error message to the user. Consider the following example.

Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.showerror("error","Error")
top.mainloop()

Output:

Dr. Yusuf Perwej


4. askquestion()

This method is used to ask some question to the user which can be answered in yes or no. Consider the
following example.

Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askquestion("Confirm","Are you sure?")
top.mainloop()

Output:

5. askokcancel()

This method is used to confirm the user's action regarding some application activity. Consider the
following example.

Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askokcancel("Redirect","Redirecting you to GITM")
top.mainloop()

Output:

6. askyesno()

This method is used to ask the user about some action to which, the user can answer in yes or no.
Consider the following example.
Dr. Yusuf Perwej
Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askyesno("Application","Got It?")
top.mainloop()

Output:

7. askretrycancel()

This method is used to ask the user about doing a particular task again or not. Consider the following
example.

Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox

top = Tk()
top.geometry("100x100")
messagebox.askretrycancel("Application","try again?")

top.mainloop()

Output:

Dr. Yusuf Perwej

You might also like