Python Unit 5
Python Unit 5
1. GU Interface
2. Python SQLite
GU Interface:
• The tkinter Module;
• Window and Widgets;
• Layout Management-
pack,
grid and
place.
Python GUI Programming With Tkinter
• Python has a lot of GUI frameworks, but Tkinter is the only framework that’s built into
the Python standard library.
• Tkinter has several strengths. It’s cross-platform, so the same code works on
Windows, macOS, and Linux.
• Visual elements are rendered using native operating system elements, so applications
built with Tkinter look like they belong on the platform where they’re run.
• One notable criticism is that GUIs built with Tkinter look outdated. If you want a shiny,
modern interface, then Tkinter may not be what you’re looking for.
Creating a window that contains a single widget.
• 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.
• The first thing you need to do is import the Python GUI Tkinter module:
Building Your First Python GUI Application With Tkinter
• The first thing you need to do is import the Python GUI Tkinter module:
import tkinter as tk
• A window is an instance of Tkinter’s Tk class. Create a new window and assign it to the
variable window:
window = tk.Tk()
• When you execute the code, a new window pops up your screen. How it looks
depends on your operating system.
• Nothing seems to happen, but notice that a new prompt does not appear in the shell.
Building Your First Python GUI Application With Tkinter
• The window.mainloop() tells Python to run the Tkinter event loop.
• This method listens for events, such as button clicks or key-presses, and blocks any
code that comes after it from running until the window it’s called on is closed.
• Go ahead and close the window you’ve created, and you’ll see a new prompt
displayed in the shell.
Structure of a Tkinter Program
import tkinter as tk import tkinter
1
window.mainloop() window.mainloop()
2
window = Tk()
window.mainloop() 3
Widget Definition
• When you use .pack() a widget into a window, Tkinter sizes the window as small as
it can while still fully encompassing the widget. Now executing the following:
window.mainloop()
• window.mainloop() tells Python to run the Tkinter event loop. This method listens
for events, such as button clicks or key-presses, and blocks any code that comes
after it from running until the window it’s called on is closed.
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.
1. Label widget: Example
root = Tk()
root.mainloop()
2. Button
• Button widget is used to add a button in your application.
• The general syntax is:
w=Button(master, option=value)
• master is the parameter used to represent the parent window.
2. Button widget: Example
r = Tk()
r.title('Counting Seconds')
r.mainloop()
3. 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)
• master is the parameter used to represent the parent window.
3. Checkbutton widget: 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)
master.mainloop()
4. Radiobutton
root = Tk()
v = IntVar()
Radiobutton(root, text='PYTHON', variable=v, value=1).pack(anchor=W)
Radiobutton(root, text='JAVA', variable=v, value=2).pack(anchor=W)
root.mainloop()
you can skip this slide during preparation: this is an extra example
from tkinter import *
root = Tk()
radio = IntVar()
R1 = Radiobutton(root,text="1st Sem",variable=radio,value=1)
R2 = Radiobutton(root,text="3rd Sem",variable=radio,value=2)
R3 = Radiobutton(root,text="5th Sem",variable=radio,value=3)
R1.pack()
R2.pack()
R3.pack()
root.mainloop()
5. Entry
• 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.
5. Entry widget: Example
from tkinter import *
master = Tk()
e1 = Entry(master)
e2 = Entry(master)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
master.mainloop()
6. 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)
• master is the parameter used to represent the parent window.
• There are number of options which are used to change the format of
the text.
6. Text widget: Example
from tkinter import *
root = Tk()
root.mainloop()
7. 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.
7. Listbox widget: Example
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()
8. 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.
8. Scale widget: Example
master = Tk()
mainloop()
9. 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)
9. Spinbox widget: Example
master = Tk()
mainloop()
10. Canvas
• The Canvas widget in Tkinter is a versatile widget that allows you to
create and manipulate 2D graphics. It provides a virtual canvas on which
you can draw various shapes and images, as well as add text and other
widgets.
• The general syntax is:
w = Canvas(master, option=value)
10. Canvas widget: Example
1. pack()
2. grid()
3. place()
tkinter also offers access to the geometric configuration of the widgets
which can organize the widgets in the parent windows.
• The 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.
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.
parent.mainloop()
2. The grid() geometry manager organizes the widgets in the
tabular form.
• We can specify the rows and columns as the options. 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.
parent.mainloop()
3. The place() geometry manager organizes the widgets to the specific x
and y coordinates.
• Anchor: It represents the exact position of the widget within the container.
The default value (direction) is NW (the upper left corner)
• height, width: It refers to the height and width in pixels.
• x, y: It refers to the horizontal and vertical offset in the pixels.
from tkinter import *
top = Tk()
top.geometry("250x170")
top.mainloop()
Python SQLite
• The SQLite3 module;
• SQLite Methods- connect, cursor, execute, close;
• Connect to Database;
• Create Table;
• Operations on Tables- Insert, Select, Update, Delete and Drop Records.
Python SQLite
• SQLite is a lightweight, serverless, and self-contained SQL database engine that is
widely used with Python.
• SQLite is designed to be fast, lightweight, and easy to use, with a small memory
footprint and low CPU usage. It stores data in a single file, making it easy to
distribute and manage, and supports many standard SQL features, such as
transactions, indexes, triggers, and views.
• SQLite is a popular choice for developers who need a local database solution that is
easy to set up and use, and does not require a dedicated server or complex
administration. It is also used as a testing and development database, and as a data
storage format for many applications and operating systems.
Python SQLite3 module
• The SQLite3 module: The sqlite3 module is a built-in module in Python that
provides a simple and easy-to-use interface for working with SQLite
databases. It allows you to create, connect to, and manipulate SQLite
databases using SQL commands.
• To use the sqlite3 module in your Python code, you first need to import it by
adding the following line at the beginning of your code:
import sqlite3 as sq or import sqlite3
Python SQLite methods
SQLite Methods - connect, cursor, execute, close: The sqlite3 module in
Python provides several methods for working with SQLite databases:
Connect to Database:
1. connect:
• connect() method: This method is used to create a connection to an SQLite
database. It takes a single argument - the name of the database file - and
returns a connection object that can be used to execute SQL commands.
• If the database file does not exist, it will be created automatically. Here's an
example:
import sqlite3 as sq
conn = sq.connect('example.db') #Create a connection to the database
Python SQLite methods
Cursor Object and its methods: A cursor object is used to interact with a
database. A cursor is created by a database connection object, and it is used to
execute SQL statements and retrieve data from the database.
2. cursor() method: This method is used to create a cursor object that can be
used to execute SQL commands. It is called on a connection object and returns
a cursor object. Here's an example:
# Create a cursor object
cur = conn.cursor()
5. fetchall() method: This method is used to fetch all the rows of a query result
set. It returns a list of tuples of values. Here's an example:
# Fetch all the rows
rows = cur.fetchall()
Python SQLite methods
6. commit() method: This method is used to save the changes made to the
database. It is called on a connection object and commits the current
transaction. Here's an example:
# Commit the changes
conn.commit()
7. close() method: This method is used to close the cursor and the connection.
It is called on both the cursor object and the connection object. Here's an
example:
# Close the cursor and the connection
cur.close()
conn.close()
Operations on tables: create, insert, select, update, delete and drop records.
import sqlite3 as sq
# create a connection to a SQLite database
conn = sq.connect('employee.db')
# create a cursor object
cur = conn.cursor()
# create a table
cur.execute("CREATE TABLE employee (id INTEGER, name TEXT)")
# insert a record in to the table
cur.execute("INSERT INTO employee (id, name) VALUES (101, 'Ravi')")
cur.execute("INSERT INTO employee(id, name) VALUES (102, 'Ravishankar')")
cur.execute("INSERT INTO employee (id, name) VALUES (103, 'Ramesh')")
# select records from the table
cur.execute("SELECT * FROM employee")
rows = cur.fetchall()
for row in rows:
print(row)
# update a record in the table
cur.execute("update employee set name ='Rakesh' where id = 101")
# delete a record from the table
cur.execute("delete from employee where id = 103")
# drop the table
cur.execute("DROP TABLE employee")
# commit the transaction
conn.commit()
# close the cursor and the connection
cur.close()
conn.close()
STEPS IN DATABASE
1. Import sqlite3 package in python file
import sqlite3
2. Connect with database/sql
conn = connect(“dbfile.db”)
3. Create a cursor object
cur = conn.cursor()
STEPS IN DATABASE
4. Execute sql queries
cursor.execute()
5. Close the connection
con.close()
Program To Check Database Connection:
This program is written to connect to database;
import sqlite3
db = sqlite3.connect("College.db")
print(db)
if(db):
print("Connection is successfull")
else:
print("Connection unsuccessfull")
5
UNIT –
3. DATA ANALYSIS
&
4. DATA VISUALISATION
DATA ANALYSIS
NumPy
• Introduction to NumPy,
• Array Creation using NumPy,
• Operations on Arrays;
Pandas
• Introduction to Pandas,
• Series and DataFrames,
• Creating DataFrames from Excel Sheet and .csv file,
• Dictionary and Tuples.
• Operations on DataFrames.
NumPy
• NumPy is a powerful Python library for numerical computing that is widely
used in data analysis.
• It provides efficient implementations of many mathematical functions and
operations on large arrays and matrices.
• Here are some of the key features of NumPy:
1. Multi-Dimensional Arrays:
• NumPy provides a powerful ndarray class for representing multi-
dimensional arrays. These arrays can have any number of dimensions, and
can be indexed and sliced in various ways.
NumPy
2. Mathematical Operations:
• NumPy provides many built-in functions for performing mathematical
operations on arrays. These functions are optimized for efficiency and can
handle large arrays with ease.
• Some examples include np.add(), np.subtract(), np.multiply(), np.divide(),
np.power(), np.sqrt(), and more.
3. Linear Algebra:
• NumPy provides a range of functions for linear algebra operations, including
matrix multiplication, determinant calculation, eigenvalue and eigenvector
calculation, and more. These functions are optimized for performance and
can handle large matrices efficiently.
NumPy
4. Random Number Generation:
• NumPy provides functions for generating random numbers from various
probability distributions. These functions are useful for many statistical and
simulation tasks.
5. Broadcasting:
• NumPy provides a powerful broadcasting feature that allows arrays with
different shapes to be used in arithmetic operations. This can simplify many
calculations and make them more efficient.
Array Creation using NumPy:
• NumPy provides several ways to create arrays in Python. Here are some of
the most common ways to create arrays using NumPy:
Here are some of the commonly used operations on arrays using NumPy:
1. add() operation / addition
2. array indexing
3. array slicing
4. reshape()
5. concatenate()
6. transpose()
7. mean()
8. sort()
Operations on Arrays:
1: add() operation and addition: to add two arrays element-wise, you can use
the numpy.add() function
Example:
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.add(a,b)
print(c) # [5, 7, 9]
Operations on Arrays:
2: array indexing: You can access elements of an array using indexing. For
example, to access the element at index 2 of an array, you can use array [2].
Ex:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
new_arr =arr.reshape((2, 3))
print(new_arr) # Output: [[1 2 3]
[4 5 6]]
Operations on Arrays:
5. concatenate(): You can concatenate two or more arrays using the
numpy.concatenate() function. For example, to concatenate two arrays a and b
vertically, you can use:
import numpy as np
a = np.array([[1, 2], [3, 4]]
b = np.array([5, 6])
c = np.concatenate((a, b), axis=0)
print(c) # Output: [[1 2]
[3 4 ]
[5 6]]
Operations on Arrays:
6. transpose (): You can transpose an array using the numpy.transpose()
function. For example, to transpose a 2-dimensional array, you can use:
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
new_arr = np.transpose(arr)
print(new_arr) # Output: [[1, 3, 5]
[2, 4, 6]]
Operations on Arrays:
7. mean (): 8. sort():
You can perform statistical You can sort the elements of an array
operations on arrays using NumPy. using the numpy.sort() function.
For example, to calculate the mean For example, to sort the elements of
of an array arr,
an array arr in ascending order, you
Ex: can use:
import numpy as np Ex: import numpy as np
arr = np.array([1, 2, 3, 4, 5])
arr =np.array([3, 1, 4, 2, 5])
mean = np.mean(arr) sorted_arr = np.sort(arr)
print(mean) print(sorted _arr)
# Output: 3.0
# Output: [1 2 3 4 5]
Operations on Arrays:
9. broadcasting(): NumPy provides broadcasting, which is a powerful
mechanism that allows you to perform arithmetic operations between arrays
with different shapes.
For example, to add a scalar value to an array arr, you can use:
Ex:
import numpy as np
arr = np.array([1, 2, 3])
new_arr = arr + 1
print(new_arr) # Output: [2 3 4]
DATA ANALYSIS
NumPy
• Introduction to NumPy,
• Array Creation using NumPy,
• Operations on Arrays;
Pandas
• Introduction to Pandas,
• Series and DataFrames,
• Creating DataFrames from Excel Sheet and .csv file,
• Dictionary and Tuples.
• Operations on DataFrames.
Pandas
Introduction to Pandas:
• Pandas is a popular open-source data analysis and manipulation library in
Python.
• It provides easy-to-use data structures and data analysis tools for handling
and manipulating numerical tables and time-series data.
• Pandas is built on top of NumPy, which makes it fast and efficient for
working with large datasets.
• Series: A one-dimensional array-like object that can hold data of any type. It
consists of a sequence of values and an associated array of labels, which is
called the index. The index can be of any type, including integers, strings, or
dates.
Filtering Rows: You can filter rows of a DataFrame using boolean indexing. For example,
df[df['column_name'] >10] filters rows where the value in column_name is greater than 10.
Sorting: You can sort a DataFrame by one or more columns using the sort_values() method.
For example, df.sort_values(by='column_name') sorts the DataFrame by column_name.
Operations on DataFrames
Aggregation: You can compute summary statistics of a DataFrame using the agg() method. For
example, df.agg({'column_name': 'mean'}) computes the mean of column_name.
Grouping: You can group a DataFrame by one or more columns using the groupby() method.
For example, df.groupby('column_name').agg({column_2': 'mean’}) groups the DataFrame by
column_name and computes the mean of column_2 for each group.
Operations on DataFrames
Joining: You can join two or more DataFrames using the merge() method. For example,
pd.merge(df1, df2, on='column_name') joins df1 and df2 on column_name.
Reshaping: You can reshape a DataFrame using the pivot() method. For example,
df.pivot(index='column_1', columns='column 2,' values='column 3') pivots the DataFrame so
that column_1 becomes the index, column_2 becomes the columns, and column_3 becomes
the values.
DATA VISUALISATION
DATA VISUALISATION
• Introduction to Data Visualisation;
• Matplotlib Library;
• Different Types of Charts using Pyplot:
• Line chart,
• Bar chart
• Histogram and
• Pie chart.
DATA VISUALISATION
• Data visualization is the process of representing data in a visual format, such
as charts, graphs, and maps, to help identify patterns, trends, and
relationships within the data.
• In Python, there are several libraries available for data visualization, such as
Matplotlib, Seaborn, Plotly, etc.
Introduction to Data Visualisation
• Data visualization can be used for exploratory data analysis, to better
understand the data and identify interesting patterns and relationships.
• Some common types of plots that can be created in Python include line
plots, scatter plots, bar plots, histograms, heatmaps, and more.
Matplotlib Library
• Matplotlib is a plotting library in Python that is widely used for creating
static, interactive, and publication-quality visualizations. It provides a wide
range of plots, including line plots, scatter plots, bar plots, histograms, and
more.
• Different Types of Charts using Pyplot- Line chart, Bar chart and Histogram
and Pie chart.
• Matplotlib's pyplot module provides a wide range of charts and plots that
can be used for data visualization. Here are some of the most commonly
used types of charts: Line Chart, Bar Chart, Pie chart and Histogram
Matplotlib Library
1. Line Chart: A line chart is used to plot a series of data points connected by
straight lines. It is useful for visualizing trends and changes over time.
3. Pie Chart: A pie chart is used to show the proportion of different categories
in a dataset. It is useful for visualizing percentages and proportions.
• We then define the x and y data arrays, which represent the x and y values of
the data points in the line chart. Also we use plt.plot() method to create line
chart.
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [3, 2, 4, 1, 5]
plt.show()
2. Bar chart: Example
• In this example, we first import the pyplot module from the matplotlib library.
We then define the x and y data arrays, which represent the categories and
values for the bar chart.
• Next, we use the plt.bar() function to create a vertical bar chart. The plt.bar()
function takes the x and y data arrays as arguments and creates a bar chart
with the categories on the x- axis and the values on the y-axis.
import matplotlib.pyplot as plt
# Sample data
x = ['A', 'B', 'C', 'D', 'E']
y = [3, 7, 2, 5, 9]
# Create vertical bar chart
plt. bar(x, y)
# Add labels and title
plt.xlabel('X-axis label')
plt.ylabel('Y-axis label"')
plt. title ('Vertical bar chart example')
# Show the plot
plt.show()
3. Pie chart: Example
• In this example, we first import the pyplot module from the matplotlib library.
We then define the sizes and labels lists, which represent the sizes and labels
of the pie chart slices.
• Next, we use the plt.pie() function to create a pie chart. The plt.pie() function
takes the sizes and labels lists as arguments and creates a pie chart with the
slices labeled with the labels.
import matplotlib.pyplot as plt
# Sample data
sizes = [30, 25, 20, 15, 10]
labels= ['A', 'B', 'C', 'D', 'E']
# Add title
plt.title('Pie chart example')
• Next, we use the plt.hist() function to create a histogram chart. The plt.hist()
function takes the data array as an argument and creates a histogram chart
with 20 bins by default.
data = [1,2,2,3,6,6,2,2,1,1,4,4,5,5,6,1,2,2]
pt.hist(data, bins=5)
pt.title("Histogram")
pt.xlabel("value")
pt.ylabel("Frequency")
pt.show()