0% found this document useful (0 votes)
62 views52 pages

Python UNIT5 Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
62 views52 pages

Python UNIT5 Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 52

PYTHON

PROGRAMMING
UNIT - 5
The tkinter Module
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.

To create a tkinter Python app, you follow these basic steps:


• Import the tkinter module: This is done just like importing any other module in
Python. Note that in Python 2.x, the module is named ‘Tkinter’, while in Python
3.x, it is named ‘tkinter’.
• Create the main window (container): The main window serves as the container
for all the GUI elements you’ll add later.
• Add widgets to the main window: You can add any number of widgets like
buttons, labels, entry fields, etc., to the main window to design the interface as
desired.
• Apply event triggers to the widgets: You can attach event triggers to the widgets
to define how they respond to user interactions.
Example:
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
Window
The foundational element of a Tkinter GUI is the window. Windows are the
containers in which all other GUI elements live. These other GUI elements, such
as text boxes, labels, and buttons, are known as widgets. Widgets are contained
inside of windows.
A window is an instance of Tkinter’s Tk class.
Widgets
There are a number of widgets which you can put in your tkinter application.
Some of the major widgets are:
• Label
• Button
• Entry
• CheckButton
• RadioButton
• Listbox
• Text
• Canvas
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.
Some Attributes of Label are: Text, Font, Size, Background, Foreground etc
Syntax:
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='welcome to GUI')
w.pack()
root.mainloop()
Button
To add a button in your application, this widget is used. 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.
Syntax:
w=Button(master, option=value)
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()
Entry
It is used to input the single line text entry from the user. For multi-line text input,
Text widget is used. 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.
Syntax:
w=Entry(master, option=value)
Example:
from tkinter import *
master = Tk()
Label(master, text='First Name').grid(row=0)
Label(master, text='Last Name').grid(row=1)
Entry
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
mainloop()
CheckButton
To select any number of options by displaying a number of options to a user as
toggle buttons.
Syntax:
w = CheckButton(master, option=value)
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()
RadioButton
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.
Syntax:
w = RadioButton(master, option=value)
Example:
from tkinter import *
root = Tk()
v = IntVar()
Radiobutton(root, text='Hi', variable=v, value=1, anchor=CENTER).pack()
Radiobutton(root, text='Hello', variable=v, value=2, anchor=CENTER).pack()
mainloop()
Listbox
It offers a list to the user from which the user can accept any number of options.
Syntax:
w = Listbox(master, option=value)
Example:
from tkinter import *
top = Tk()
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.pack()
top.mainloop()
Text
To edit a multi-line text and format the way it has to be displayed.
Syntax:
w = Text(master, option=value)Example:
from tkinter import *
root = Tk()
T = Text(root, height=2, width=30)
T.pack()
T.insert(END, 'IndianCricketTeam\nCHAMPIONS\n')
mainloop()
Canvas
It is used to draw pictures and other complex layout like graphics, text and
widgets.
Syntax:
w = Canvas(master, option=value)
Example:
from tkinter import *
master = Tk()
w = Canvas(master, width=40, height=60)
w.pack()
Canvas
canvas_height=20
canvas_width=200
y = int(canvas_height / 2)
w.create_line(0, y, canvas_width, y )
mainloop()
Layout 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.
grid() method
It organizes the widgets in grid (table-like structure) before placing in the parent
widget.
place() method
It organizes the widgets by placing them on specific positions directed by the
programmer.
Pack
This geometry manager organizes widgets in blocks before placing them in the
parent widget.
import tkinter as tk
root = tk.Tk()
root.title("Pack Example")
button1 = tk.Button(root, text="Button 1") #Create three buttons
button2 = tk.Button(root, text="Button 2")
button1.pack() # Pack the buttons vertically
button2.pack()
root.mainloop()
Grid
This geometry manager organizes widgets in a table-like structure in the parent
widget.
import tkinter as tk
root = tk.Tk()
root.title("Grid Example")
label1 = tk.Label(root, text="Label 1") # Create three labels
label2 = tk.Label(root, text="Label 2")
label1.grid(row=0, column=0) # Grid the labels in a 2x2 grid
label2.grid(row=0, column=1)
root.mainloop()
Place
This geometry manager organizes widgets by placing them in a specific position
in the parent widget.
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)
root.mainloop()
The SQLite3 module
Python SQLite3 module is used to integrate the SQLite database with Python. It
is a standardized Python DBI API 2.0 and provides a straightforward and simple-
to-use interface for interacting with SQLite databases. There is no need to
install this module separately as it comes along with Python after the 2.5x
version.
SQLite Methods
Connect
import sqlite3
# Connect to an SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db’)

Cursor
# Create a cursor object using the cursor() method
cursor = conn.cursor()

Execute
# Create table
cursor.execute('''CREATE TABLE IF NOT EXISTS stocks
(date text, trans text, symbol text, qty real, price real)'‘’)
# Insert a row of data
cursor.execute("INSERT INTO stocks VALUES ('2006-01-
05','BUY','RHAT',100,35.14)")

Commit
# Save (commit) the changes
conn.commit()

Close
# Close the connection
conn.close()
Connect to Database
Connecting to the SQLite Database can be established using the connect()
method, passing the name of the database to be accessed as a parameter. If
that database does not exist, then it’ll be created.
sqliteConnection = sqlite3.connect('sql.db’)

But what if you want to execute some queries after the connection is being
made. For that, a cursor has to be created using the cursor() method on the
connection instance, which will execute our SQL queries.
cursor = sqliteConnection.cursor()
print('DB Init')
Create Table
Syntax:
CREATE TABLE database_name.table_name(
column1 datatype PRIMARY KEY(one or more columns),
column2 datatype,
column3 datatype,
…..
columnN datatype
);
Steps to Create a Table:
Import the required module
Establish the connection or create a connection object with the database using
the connect() function of the sqlite3 module.
Create a Cursor object by calling the cursor() method of the Connection object.
Form table using the CREATE TABLE statement with the execute() method of the
Cursor class.
Example:
import sqlite3
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('geek.db')
# cursor object
cursor_obj = connection_obj.cursor()
# Drop the GEEK table if already exists.
cursor_obj.execute("DROP TABLE IF EXISTS GEEK")
# Creating table
table = """ CREATE TABLE GEEK (
Email VARCHAR(255) NOT NULL,
First_Name CHAR(25) NOT NULL,
Last_Name CHAR(25),
Score INT
); """
cursor_obj.execute(table)
print("Table is Ready")
# Close the connection
connection_obj.close()
Operations on Tables
INSERT - The SQL INSERT INTO statement of SQL is used to insert a new row in a
table.
SELECT - This statement is used to retrieve data from an SQLite table and this
returns the data contained in the table.
UPDATE - The UPDATE statement in SQL is used to update the data of an existing
table in the database. We can update single columns as well as multiple columns
using UPDATE statement as per our requirement.
DELETE - SQLite database we use the DELETE statement to delete data from a table.
DROP - DROP is used to delete the entire database or a table. It deleted both
records in the table along with the table structure.
Operations on Tables – Insert Records
Syntax:
INSERT INTO table_name VALUES (value1, value2, value3,…);
table_name: name of the table.
value1, value2,.. : value of first column, second column,… for the new record
Example:
# Creating table
table ="""CREATE TABLE STUDENT(NAME VARCHAR(255), CLASS VARCHAR(255),
SECTION VARCHAR(255));"""
cursor.execute(table)
# Queries to INSERT records.
cursor.execute('''INSERT INTO STUDENT VALUES ('Raju', '7th', 'A')''')
Operations on Tables – Select Records
Syntax:
SELECT * FROM table_name;
* : means all the column from the table
To select specific column replace * with the column name or column names.

Syntax:
cursor.fetchall()
where, cursor is an object of sqlite3 connection with database.
To fetch all records we will use fetchall() method.
Operations on Tables – Select Records
Example:
statement = '''SELECT * FROM GEEK'''
cursor_obj.execute(statement)
output = cursor_obj.fetchall()
for row in output:
print(row)
connection_obj.commit()
# Close the connection
connection_obj.close()
Operations on Tables – Update Records
Syntax:
UPDATE table_name SET column1 = value1, column2 = value2,…
WHERE condition;
Example:
# Updating Data
cursor.execute('''UPDATE EMPLOYEE SET INCOME = 5000 WHERE Age<25;''')
print('\nAfter Updating...\n')
# Display data
print("EMPLOYEE Table: ")
data = cursor.execute('''SELECT * FROM EMPLOYEE''')
for row in data:
print(row)
Operations on Tables – Delete Records
Syntax:
DELETE FROM table_name [WHERE Clause]

Example:
#delete data
cursor_obj.execute("DELETE FROM STUDENT WHERE Score < 15")

connection_obj.commit()
# Close the connection
connection_obj.close()
Operations on Tables – Drop Records
Syntax:
DROP TABLE TABLE_NAME;

Example:
# drop table
connection.execute("DROP TABLE STUDENT ") #student is the tablename
print("data dropped successfully")

# close the connection


connection.close()
NumPy - Introduction to NumPy
NumPy is a Python library used for working with arrays. It also has functions for
working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and
you can use it freely. NumPy stands for Numerical Python.
Why to use NumPy Arrays?
In Python we have lists that serve the purpose of arrays, but they are slow to
process.
NumPy aims to provide an array object that is up to 50x faster than traditional
Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting
functions that make working with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are
very important.
Array Creation using NumPy
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
We can create a NumPy ndarray object by using the array() function.
Example:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
print(type(arr))

import numpy as np
arr = np.array((1, 2, 3, 4, 5))
print(arr)
Operations on Arrays
Note: These are operations on NumPy Arrays, Array & NumPy Arrays are
different.

# Python code to perform arithmetic operations on NumPy array


import numpy as np
arr1 = np.array([10, 8]) # Initializing the array
print('First array:')
print(arr1)

print('\nSecond array:')
arr2 = np.array([12, 12])
print(arr2)
[22 20]
[-2 -4]
print('\nAdding the two arrays:')
0.83333333 0.66666667

print(np.add(arr1, arr2)) #[22 20]

print('\nSubtracting the two arrays:')


print(np.subtract(arr1, arr2)) #[-2 -4]

print('\nMultiplying the two arrays:')


print(np.multiply(arr1, arr2)) #[120 96]

print('\nDividing the two arrays:')


print(np.divide(arr1, arr2)) #[0.83333333 0.66666667]
import numpy as np
arr = np.array([5, 10, 15])
arr1 = np.array([1, 2, 3])
print('\nApplying power function:')
print(np.power(arr, arr1)) #[ 5 100 3375]

print('\nApplying mod() function:')


print(np.mod(arr, arr1)) #[0, 0, 0]

print('\nApplying remainder() function:')


print(np.remainder(arr, arr1)) #[0, 0, 0]
Pandas- Introduction to Pandas
Pandas is a Python library used for working with data sets. It has functions for
analyzing, cleaning, exploring, and manipulating data. The name "Pandas" has a
reference to both "Panel Data", and "Python Data Analysis" and was created by
Wes McKinney in 2008.

Why to use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical
theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.
Series
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
Example:
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)

If nothing else is specified, the values are labeled with their index number. First
value has index 0, second value has index 1 etc. This label can be used to access
a specified value.
print(myvar[0])
Series - Lables
With the index argument, you can name your own labels.
Example:
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a, index = ["x", "y", "z"])
print(myvar)

When you have created labels, you can access an item by referring to the label.
print(myvar["y"])
DataFrames
A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional
array, or a table with rows and columns.
Example:
import pandas as pd
data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}
#load data into a DataFrame object:
df = pd.DataFrame(data)
print(df)
DataFrames – Locate Row
As you can see from the result above, the DataFrame is like a table with rows
and columns.
Pandas use the loc attribute to return one or more specified row(s)
Example:
#refer to the row index:
print(df.loc[0])

#use a list of indexes:


print(df.loc[[0, 1]])
Introduction to Data Visualisation
In today’s world, a lot of data is being generated on a daily basis. And sometimes to
analyze this data for certain trends, patterns may become difficult if the data is in
its raw format. To overcome this data visualization comes into play. Data
visualization provides a good, organized pictorial representation of the data which
makes it easier to understand, observe, analyze.

Python provides various libraries that come with different features for visualizing
data. All these libraries come with different features and can support various types
of graphs. Some of the libraries are listed below:
Matplotlib
Seaborn
Bokeh
Matplotlib Library
Matplotlib is an easy-to-use, low-level data visualization library that is built on
NumPy arrays. It consists of various plots like scatter plot, line plot, histogram, etc.
Matplotlib provides a lot of flexibility.
To install this type the below command in the terminal.
pip install matplotlib
Different Types of Charts using Pyplot -
Line chart
Line Chart is used to represent a relationship between two data X and Y on a
different axis. It is plotted using the plot() function.
Example:
import matplotlib.pyplot as plt

x=[20,10,40,2,45,67]
y=[10,20,30,40,50,60]
plt.figure(figsize=(8,6))
plt.title("Line Plot Graph",fontsize=15,color='red')
plt.xlabel("X Axis",fontsize=12,color='blue')
Line chart
plt.ylabel("Y Axis",fontsize=12,color='blue')
plt.plot(x,y,color="purple",linewidth=5,label="Line Plot")
plt.legend(loc=1,fontsize=12)
plt.show()
Bar chart
A bar plot or bar chart is a graph that represents the category of data with
rectangular bars with lengths and heights that is proportional to the values which
they represent. It can be created using the bar() method.

Example:
import matplotlib.pyplot as plt

x=[20,10,30,40,2,45,67]
y=[10,25,30,40,50,60,42]
plt.figure(figsize=(8,6))
plt.title("Bar Plot Graph",fontsize=15,color='red')
Bar chart
plt.xlabel("X Axis",fontsize=12,color='blue')
plt.ylabel("Y Axis",fontsize=12,color='blue')
plt.bar(x,y,color="purple",linewidth=5,label="Bar Plot")
plt.legend(loc=1,fontsize=12)
plt.show()
Histogram
A histogram is basically used to represent data in the form of some groups. It is a
type of bar plot where the X-axis represents the bin ranges while the Y-axis gives
information about frequency. The hist() function is used to compute and create a
histogram. In histogram, if we pass categorical data then it will automatically
compute the frequency of that data i.e. how often each value occurred.
Example:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1) #generates random integers
data=np.random.randint(1,100,50)
plt.title("Histogram Plot",fontsize=15,color="red")
Histogram
plt.xlabel("X Axis",fontsize=12,color="blue")
plt.ylabel("Y Axis",fontsize=12,color="blue")
plt.hist(data)
plt.show()
Pie chart
A Pie Chart is a circular statistical plot that can display only one series of data. The
area of the chart is the total percentage of the given data. Pie charts are commonly
used in business presentations like sales, operations, survey results, resources, etc.
as they provide a quick summary.
Example:
import matplotlib.pyplot as plt
data=[78,90,10,45,35]
lab=["A","B","C","D","E"]
col=["red","orange","blue","green","yellow"]
plt.figure(figsize=(6,6))
plt.title("Pie Plot",fontsize=15,color="red")
plt.pie(data,colors=col,labels=lab,autopct="%.2f%%")
plt.show()

You might also like