Unit 5
Unit 5
Python provides the standard library Tkinter for creating the graphical user interface for
desktop based applications.
Developing desktop based applications with python Tkinter is not a complex task. An empty
Tkinter top-level window can be created by using the following steps.
Example
1. # !/usr/bin/python3
2. from tkinter import *
3. #creating the application main window.
4. top = Tk()
5. #Entering the event main loop
6. top.mainloop()
Output:
Tkinter widgets
There are various widgets like button, canvas, checkbutton, entry, etc. that are used to build
the python GUI applications.
S Widget Description
N
1 Button The Button is used to add various kinds of buttons to the python
application.
2 Canvas The canvas widget is used to draw the canvas on the window.
4 Entry The entry widget is used to display the single-line text field to the
user. It is commonly used to accept user values.
7 ListBox The ListBox widget is used to display a list of options to the user.
8 Menubutton The Menubutton is used to display the menu items to the user.
13 Scrollbar It provides the scrollbar to the user so that the user can scroll the
window up and down.
The Tkinter geometry specifies the method by using which, the widgets are represented on
display. The python Tkinter provides the following geometry methods.
However, the controls are less and widgets are generally added in the less organized manner.
syntax
1. widget.pack(options)
o expand: If the expand is set to true, the widget expands to fill any space.
o 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.
o 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
widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
o Column
The column number in which the widget is to be placed. The leftmost column is
represented by 0.
o Columnspan
The width of the widget. It represents the number of columns up to which, the column
is expanded.
o ipadx, ipady
It represents the number of pixels to pad the widget inside the widget's border.
o padx, pady
It represents the number of pixels to pad the widget outside the widget's border.
o row
The row number in which the widget is to be placed. The topmost row is represented
by 0.
o rowspan
The height of the widget, i.e. the number of the row up to which the widget is
expanded.
o 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:
The place() geometry manager organizes the widgets to the specific x and y coordinates.
Syntax
1. widget.place(options)
o Anchor: It represents the exact position of the widget within the container. The
default value (direction) is NW (the upper left corner)
o 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.
o height, width: It refers to the height and width in pixels.
o relheight, relwidth: It is represented as the float between 0.0 and 1.0 indicating the
fraction of the parent's height and width.
o relx, rely: It is represented as the float between 0.0 and 1.0 that is the offset in the
horizontal and vertical direction.
o 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:
PlayNext
Unmute
Current Time 0:00
Duration 18:10
Loaded: 0.37%
Â
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s
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.
Syntax
1. W = Button(parent, options)
SN Option Description
2 activeforeground It represents the font color of the button when the mouse hover
the button.
10 Highlightcolor The color of the highlight when the button has the focus.
12 justify It illustrates the way by which the multiple text lines are
represented. It is set to LEFT for left justification, RIGHT for
the right justification, and CENTER for the center.
20 Wraplength If the value is set to a positive number, the text lines will be
wrapped to fit within this length.
Example
1. #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()
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=1
0)
b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink",pady
= 10)
b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",pad
y = 10)
b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)
top.mainloop()
Output:
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
1. w = canvas(parent, options)
SN Option Description
3 confine It is set to make the canvas unscrollable outside the scroll region.
4 cursor The cursor is used as the arrow, circle, dot, etc. on the canvas.
7 relief It represents the type of the border. The possible values are SUNKEN, RAIS
GROOVE, and RIDGE.
8 scrollregion It represents the coordinates specified as the tuple containing the area of the canva
10 xscrollincremen If it is set to a positive value. The canvas is placed only to the multiple of this valu
t
11 xscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the horiz
scrollbar.
13 yscrollcommand If the canvas is scrollable, this attribute should be the .set() method of the ve
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()
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:
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 – Packages
A python package is a collection of modules. Modules that are related to each other are
mainly put in the same package. When a module from an external package is required
in a program, that package can be imported and its modules can be put to use.
We organize a large number of files in different folders and subfolders based on some
criteria, so that we can find and manage them easily. In the same way, a package in Python
takes the concept of the modular approach to next logical level. As you know,
a module can contain multiple objects, such as classes, functions, etc. A package can
contain one or more relevant modules. Physically, a package is actually a folder containing
one or more module files.
greet.py
Copy
def SayHello(name):
print("Hello ", name)
functions.py
Copy
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
That's it. We have created our package called mypackage. The following is a folder
structure:
Now, to test our package, navigate the command prompt to the MyApp folder and invoke
the Python prompt from there.
D:\MyApp>python
Import the functions module from the mypackage package and call its power() function.
>>> functions.power(3,2)
>>> sum(10,20)
30
>>> average(10,12)
5.2M
56
__init__.py
The package folder contains a special file called __init__.py, which stores the package's
content. It serves two purposes:
An empty __init__.py file makes all functions from the above modules available when this
package is imported. Note that __init__.py is essential for the folder to be recognized by
Python as a package. You can optionally define functions from individual modules to be
made available.
Note:
We shall also create another Python script in the MyApp folder and import the mypackage
package in it. It should be at the same level of the package to be imported.
The __init__.py file is normally kept empty. However, it can also be used to choose
specific functions from modules in the package folder and make them available for import.
Modify __init__.py as below:
__init__.py
Copy
The specified functions can now be imported in the interpreter session or another
executable script.
test.py
Copy
Note that functions power() and SayHello() are imported from the package and not from
their respective modules, as done earlier. The output of the above script is:
D:\MyApp>python test.py
Hello world
power(3,2) : 9
Once a package is created, it can be installed for system-wide use by running the setup
script. The script calls setup() function from the setuptools module.
Save the following code as setup.py in the parent folder MyApp. The script calls
the setup() function from the setuptools module. The setup() function takes various
arguments such as name, version, author, list of dependencies, etc. The zip_safe argument
defines whether the package is installed in compressed mode or regular mode.
Example: setup.py
Copy
Processing d:\MyApp
Now mypackage is available for system-wide use and can be imported in any script or
interpreter.
D:\>python
>>>mypackage.average(10,20)
15.0
>>>mypackage.power(10,2)
100
You may also want to publish the package for public use. PyPI (stands for Python Package
Index) is a repository of Python packages.
Visit https://packaging.python.org/distributing to know more about the procedure of
uploading a package to PyPI.
Python is increasingly being used as a scientific language. Matrix and vector manipulations
are extremely important for scientific computations. Both NumPy and Pandas have emerged
to be essential libraries for any scientific computation, including machine learning, in python
due to their intuitive syntax and high-performance matrix computation capabilities.
In this post, we will provide an overview of the common functionalities of NumPy and
Pandas. We will realize the similarity of these libraries with existing toolboxes in R and
MATLAB. This similarity and added flexibility have resulted in wide acceptance of python
in the scientific community lately. Topic covered in the blog are:
1. Overview of NumPy
2. Overview of Pandas
3. Using Matplotlib
This post is an excerpt from a live hands-on training conducted by CloudxLab on 25th
Nov 2017. It was attended by more than 100 learners around the globe. The participants were
from countries namely; United States, Canada, Australia, Indonesia, India, Thailand,
Philippines, Malaysia, Macao, Japan, Hong Kong, Singapore, United Kingdom, Saudi
Arabia, Nepal, & New Zealand.
What is NumPy?
NumPy stands for ‘Numerical Python’ or ‘Numeric Python’. It is an open source module of
Python which provides fast mathematical computation on arrays and matrices. Since, arrays
and matrices are an essential part of the Machine Learning ecosystem, NumPy along with
Machine Learning modules like Scikit-learn, Pandas, Matplotlib, TensorFlow, etc. complete
the Python Machine Learning Ecosystem.
NumPy’s main object is the homogeneous multidimensional array. It is a table with same
type elements, i.e, integers or string or characters (homogeneous), usually integers. In
NumPy, dimensions are called axes. The number of axes is called the rank.
There are several ways to create an array in NumPy like np.array, np.zeros, no.ones, etc. Each
of them provides some flexibility.
>>> np.random.rand(2,3)
np.random.rand(2,3) array([[ 0.55365951, 0.60150511, 0.36113117],
[ 0.5388662 , 0.06929014, 0.07908068]])
>>> np.empty((2,3))
np.empty((2,3)) array([[ 0.21288689, 0.20662218, 0.78018623],
[ 0.35294004, 0.07347101, 0.54552084]])
Some of the important attributes of a NumPy object are:
NumPy array elements can be accessed using indexing. Below are some of the useful
examples:
The session covers these and some important attributes of the NumPy array object in detail.
Machine learning uses vectors. Vectors are one-dimensional arrays. It can be represented
either as a row or as a column array.
What are vectors? Vector quantity is the one which is defined by a magnitude and a direction.
For example, force is a vector quantity. It is defined by the magnitude of force as well as a
direction. It can be represented as an array [a,b] of 2 numbers = [2,180] where ‘a’ may
represent the magnitude of 2 Newton and 180 (‘b’) represents the angle in degrees.
Another example, say a rocket is going up at a slight angle: it has a vertical speed of 5,000
m/s, and also a slight speed towards the East at 10 m/s, and a slight speed towards the North
at 50 m/s. The rocket’s velocity may be represented by the following vector: [10, 50, 5000]
which represents the speed in each of x, y, and z-direction.
Similarly, vectors have several usages in Machine Learning, most notably to represent
observations and predictions.
For example, say we built a Machine Learning system to classify videos into 3 categories
(good, spam, clickbait) based on what we know about them. For each video, we would have a
vector representing what we know about it, such as: [10.5, 5.2, 3.25, 7.0]. This vector could
represent a video that lasts 10.5 minutes, but only 5.2% viewers watch for more than a
minute, it gets 3.25 views per day on average, and it was flagged 7 times as spam.
As you can see, each axis may have a different meaning. Based on this vector, our Machine
Learning system may predict that there is an 80% probability that it is a spam video, 18% that
it is clickbait, and 2% that it is a good video. This could be represented as the following
vector: class_probabilities = [0.8,0.18,0.02].
As can be observed, vectors can be used in Machine Learning to define observations and
predictions. The properties representing the video, i.e., duration, percentage of viewers
watching for more than a minute are called features.
Since the majority of the time of building machine learning models would be spent in data
processing, it is important to be familiar to the libraries that can help in processing such data.
Pandas
Similar to NumPy, Pandas is one of the most widely used python libraries in data science. It
provides high-performance, easy to use structures and data analysis tools. Unlike NumPy
library which provides objects for multi-dimensional arrays, Pandas provides in-memory 2d
table object called Dataframe. It is like a spreadsheet with column names and row labels.
Hence, with 2d tables, pandas is capable of providing many additional functionalities like
creating pivot tables, computing columns based on other columns and plotting graphs. Pandas
can be imported into Python using:
Pandas Series object is created using pd.Series function. Each row is provided with an index
and by defaults is assigned numerical values starting from 0. Like NumPy, Pandas also
provide the basic mathematical functionalities like addition, subtraction and conditional
operations and broadcasting.
Pandas dataframe object represents a spreadsheet with cell values, column names, and row
index labels. Dataframe can be visualized as dictionaries of Series. Dataframe rows and
columns are simple and intuitive to access. Pandas also provide SQL-like functionality to
filter, sort rows based on conditions. For example,
>>> people
New columns and rows can be easily added to the dataframe. In addition to the basic
functionalities, pandas dataframe can be sorted by a particular column.
Dataframes can also be easily exported and imported from CSV, Excel, JSON, HTML and
SQL database. Some other essential methods that are present in dataframes are:
What is matplotlib?
>>> num_bins = 5
>>> plt.show()
>>> plt.show()