Unit – 4
GUInterface:ThetkinterModule;WindowandWidgets;LayoutManagement-pack,gridand
[Link]:TheSQLite3module;SQLiteMethods-connect,cursor,execute,close;
Connect to Database; Create Table; Operations on Tables- Insert, Select, Update. Delete and
[Link]:NumPy-IntroductiontoNumPy,ArrayCreationusingNumPy,
Operations on Arrays; Pandas- Introduction to Pandas, Series and DataFrames, Creating
[Link],[Link]
isualisation:IntroductiontoDataVisualisation;MatplotlibLibrary;DifferentTypesofCharts using
Pyplot- Line chart, Bar chart and Histogram and Pie chart.
GUI Programming with Tkinter
TKinter is an open-source and standard GUI toolkit for Python. TKinter is a wrapper around tcl / TK
graphical interface. TKinter is popular because of its simplicity and having a very old and active
community. Also, it comes included with most binary distributions of Python. TKinter is fully portable for
Macintosh, Windows, and Linux platforms. It’s a good toolkit to start with since TKinter is mostly preferred
for small-scale GUI applications.
Why and When Use Tkinter?
Tkinter is best used when we want to build applications with buttons, text boxes, menus and other
interactive elements. Tkinter is commonly employed for making desktop applications, ranging from simple
tools to more complex software. It is specially used for projects where a user friendly interface is necessary.
Whether you’re creating a calculator, a game, or a data visualization tool, Tkinter provides a straightforward
way to design and implement GUIs in Python.
Features of Tkinter
• Lightweight: Tkinter is included with Python’s standard library, making it lightweight and easily
accessible.
• Simple to learn: It has a straightforward syntax, making it suitable for beginners to quickly grasp
and start building GUI applications.
• Rapid prototyping: Ideal for rapid application development due to its simplicity and ease of use.
• Good for basic GUIs: Well-suited for creating simple graphical user interfaces for small to medium-
sized projects.
Pros of Tkinter Cons of Tkinter
Excellent documentation Larger memory footprint
Lightweight and bundled with Python Limited built-in widgets
Simplicity in basic GUI development Less modern appearance
The tkinter Module
➢ The tkinter module is the standard GUI library in Python, providing a set of widgets and tools for
building graphical user interfaces.
import tkinter as tk
root = [Link]()
label = [Link](root, text="Hello, World!")
[Link]()
[Link]()
Window and Widgets
Tkinter is the standard GUI (Graphical User Interface) toolkit for Python. It provides a simple way to create
windows and various widgets that allow users to interact with applications.
Key Concepts
1. Main Window
The main window is the primary container for all other widgets.
It is created using the Tk() class.
import tkinter as tk
root = [Link]()
[Link]("My Application")
[Link]("400x300")
[Link]()
2. Widgets
Widgets are the building blocks of a Tkinter application. Common widgets include:
a. Label: Displays text or images. Use Label() to create.
b. Button: Triggers an action when clicked. Use Button() to create.
c. Entry: A single-line text input field. Use Entry() to create.
d. Text: A multi-line text input field. Use Text() to create.
e. Frame: A container for organizing widgets. Use Frame() to create.
Example:
import tkinter as tk
def display_text():
input_text = [Link]()
text_area.delete(1.0, [Link]) # Clear previous text
text_area.insert([Link], input_text) # Insert new text
# Create the main window
root = [Link]()
[Link]("Simple Tkinter Program")
[Link]("400x300")
# Create a Frame
frame = [Link](root)
[Link](pady=20)
# Label
label = [Link](frame, text="Enter some text:")
[Link](pady=5)
# Entry
entry = [Link](frame, width=30)
[Link](pady=5)
# Button
submit_button = [Link](frame, text="Display Text", command=display_text)
submit_button.pack(pady=10)
# Text
text_area = [Link](root, height=10, width=40)
text_area.pack(pady=20)
# Run the application
[Link]()
Example 2: The Tk() function creates the main window, and various widgets
(e.g., Label, Button, Entry) can be added to the window.
button1 = [Link](root, text="Click me!")
[Link]()
3. Layout Management
Tkinter provides three layout managers to organize widgets:
a) pack(): Packs widgets into the parent widget in a block.
b) grid(): Places widgets in a 2D grid.
c) place(): Places widgets at an absolute position.
Example:
import tkinter as tk
def show_message():
message_label.config(text="Button Clicked!")
# Create the main window
root = [Link]()
[Link]("Layout Managers Example")
[Link]("400x300")
# Using pack layout manager for the title label
title_label = [Link](root, text="Layout Managers in Tkinter", font=("Arial", 16))
title_label.pack(pady=10)
frame = [Link](root)
[Link](pady=20)
# Using grid layout manager for input fields and button
# Label and Entry for Name
name_label = [Link](frame, text="Name:")
name_label.grid(row=0, column=0, padx=5, pady=5)
name_entry = [Link](frame)
name_entry.grid(row=0, column=1, padx=5, pady=5)
# Label and Entry for Age
age_label = [Link](frame, text="Age:")
age_label.grid(row=1, column=0, padx=5, pady=5)
age_entry = [Link](frame)
age_entry.grid(row=1, column=1, padx=5, pady=5)
# Button to show message
show_button = [Link](frame, text="Show Message", command=show_message)
show_button.grid(row=2, columnspan=2, pady=10)
# Using place layout manager for a message label
message_label = [Link](root, text="", font=("Arial", 12))
message_label.place(relx=0.5, rely=0.8, anchor='center')
# Run the application
[Link]()
Example 2: Tkinter provides three main layout managers: pack(), grid(), and place().
button1 = [Link](root, text="Button 1")
button2 = [Link](root, text="Button 2")
[Link](row=0, column=0)
[Link](row=0, column=1)
Event Handling
Tkinter supports event-driven programming. You can bind events to widgets using the bind() method.
def on_key_press(event):
print(f"Key pressed: {[Link]}")
[Link]("<Key>", on_key_press)
Python SQLite
SQLite is a lightweight, serverless, self-contained SQL database engine. It is widely used for applications
that require a simple database solution without the overhead of a full database server.
The SQLite3 Module
Python provides an interface to SQLite databases through the sqlite3 module, which allows you to create,
connect, and manipulate SQLite databases using Python code.
Key SQLite Methods
• connect(): Establishes a connection to an SQLite database file.
• cursor(): Creates a cursor object, which allows you to execute SQL commands.
• execute(): Executes an SQL command using the cursor.
• close(): Closes the database connection.
Connecting to a Database
To connect to a database, use the connect() method. If the database file does not exist, it will be created.
import sqlite3
# Connect to the database (or create it)
connection = [Link]('[Link]')
Creating a Table
To create a table, you need to define the structure of the table and execute a CREATE TABLE SQL
statement.
# Create a cursor object
cursor = [Link]()
# Create a table
[Link]('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL
)
''')
# Commit the changes
[Link]()
Operations on Tables
1. Insert Records
To insert records into a table, use the INSERT INTO SQL statement.
# Insert a record
[Link]('''
INSERT INTO users (name, age) VALUES (?, ?)
''', ('Alice', 30))
# Commit the changes
[Link]()
2. Select Records
To retrieve records, use the SELECT statement.
# Select all records
[Link]('SELECT * FROM users')
rows = [Link]()
for row in rows:
print(row)
3. Update Records
To update existing records, use the UPDATE statement.
# Update a record
[Link]('''
UPDATE users SET age = ? WHERE name = ?
''', (31, 'Alice'))
# Commit the changes
[Link]()
4. Delete Records
To delete records from a table, use the DELETE statement.
#Delete a record
[Link]('''
DELETE FROM users WHERE name = ?
''', ('Alice',))
# Commit the changes
[Link]()
5. Drop Records
To drop a table, use the DROP TABLE statement.
# Drop the table
[Link]('DROP TABLE IF EXISTS users')
# Commit the changes
[Link]()
Closing the Connection
Once you are done with the database operations, it is important to close the connection.
# Close the cursor and connection
[Link]()
[Link]()
Complete Example
Here’s a complete example that incorporates all the above operations:
import sqlite3
# Connect to the database
connection = [Link]('[Link]')
cursor = [Link]()
# Create a table
[Link]('''
CREATE TABLE IF NOT EXISTS users
( id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER NOT NULL
)
''')
# Insert records
[Link]('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice',
30))
[Link]('INSERT INTO users (name, age) VALUES (?, ?)', ('Bob', 25))
[Link]()
# Select records
[Link]('SELECT * FROM users')
print("Users before update:")
for row in [Link]():
print(row)
# Update a record
[Link]('UPDATE users SET age = ? WHERE name = ?', (31, 'Alice'))
[Link]()
# Select records after update
[Link]('SELECT * FROM users')
print("Users after update:")
for row in [Link]():
print(row)
# Delete a record
[Link]('DELETE FROM users WHERE name = ?', ('Bob',))
[Link]()
# Drop the table
[Link]('DROP TABLE IF EXISTS users')
[Link]()
# Close the cursor and connection
[Link]()
[Link]()
Note:
• The sqlite3 module provides a simple way to interact with SQLite databases in Python.
• Common operations include connecting to a database, creating tables, inserting, selecting, updating,
deleting, and dropping records.
• Always remember to commit your changes and close the connection when done.
Data Analysis with NumPy and Pandas
Data analysis involves inspecting, cleaning, and modeling data to discover useful information, inform
conclusions, and support decision-making. Python provides powerful libraries such as NumPy and Pandas
for data manipulation and analysis.
NumPy
Introduction to NumPy
NumPy (Numerical Python) is a fundamental library for numerical computations in Python. It provides
support for arrays, matrices, and a variety of mathematical functions to operate on these data structures.
Array Creation using NumPy
You can create arrays in several ways using NumPy:
Creating a 1D Array:
import numpy as np
array_1d = [Link]([1, 2, 3, 4, 5])
Creating a 2D Array:
array_2d = [Link]([[1, 2, 3], [4, 5, 6]])
Using NumPy Functions:
Zeros Array:
zeros_array = [Link]((2, 3)) # 2x3 array of zeros
Ones Array:
ones_array = [Link]((3, 2)) # 3x2 array of ones
Random Array:
random_array = [Link](3, 3) # 3x3 array of random numbers
Operations on Arrays
NumPy supports a wide range of operations on arrays:
Element-wise Operations:
array_a = [Link]([1, 2, 3])
array_b = [Link]([4, 5, 6])
sum_array = array_a + array_b # Element-wise addition
Mathematical Functions:
mean_value = [Link](array_a) # Mean
max_value = [Link](array_a) # Maximum
Array Reshaping:
reshaped_array = array_2d.reshape((3, 2)) # Reshape to 3x2
Indexing and Slicing:
element = array_1d[2] # Accessing the third element
sliced_array = array_2d[:, 1] # Accessing the second column
Pandas
Introduction to Pandas
Pandas is a powerful data manipulation and analysis library. It provides data structures such as Series and
DataFrames, which are essential for handling structured data.
Series and DataFrames
Series:
One-dimensional: It holds a single column of data.
Labeled array: Each element has an index (label).
Homogeneous: It typically holds data of a single type (e.g., all numbers, all strings).
Example: Imagine a list of names or a list of temperatures; each value has an index.
Series Creation Example:
import pandas as pd
series = [Link]([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
DataFrame:
Two-dimensional: It's like a spreadsheet or a table with rows and columns.
Labeled: Both rows and columns have labels (indices and column names).
Heterogeneous: It can hold multiple columns with potentially different data types.
Example: A table with columns like "Name", "Age", and "City". Each column is a Series, and the entire
table is a DataFrame.
DataFrame Creation Example:
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = [Link](data)
Creating DataFrames from Excel and CSV Files
From a CSV File:
df_csv = pd.read_csv('[Link]') # Load DataFrame from a CSV file
From an Excel Sheet:
df_excel = pd.read_excel('[Link]', sheet_name='Sheet1')
# Load DataFrame from an Excel file
Creating DataFrames from Dictionary and Tuples
From a Dictionary:
data_dict = {
'Name': ['Alice', 'Bob'],
'Age': [25, 30] }
df_from_dict = [Link](data_dict)
From Tuples:
data_tuples = [('Alice', 25), ('Bob', 30)]
df_from_tuples = [Link](data_tuples, columns=['Name',
'Age'])
Operations on DataFrames
Viewing Data:
print([Link]()) # Display the first 5 rows
print([Link]()) # Display the last 5 rows
Selecting Columns:
ages = df['Age'] # Accessing a column
Filtering Rows:
filtered_df = df[df['Age'] > 30] # Filter rows where Age > 30
Adding a New Column:
df['Salary'] = [50000, 60000, 70000] # Adding a new column
Updating Values:
[Link][df['Name'] == 'Alice', 'Age'] = 26 # Update Alice's age
Deleting a Column:
[Link]('Salary', axis=1, inplace=True) # Drop the Salary column
Group By:
grouped = [Link]('City').mean()
# Group by City and calculate mean
Saving DataFrame to CSV:
df.to_csv('[Link]', index=False) # Save DataFrame to a CSV file
Data Visualization with Matplotlib
Data visualization is the graphical representation of information and data. By using visual elements like
charts, graphs, and maps, data visualization tools provide an accessible way to see and understand trends,
outliers, and patterns in data.
Introduction to Data Visualization
Purpose: To communicate data clearly and effectively through graphical means.
Benefits:
• Simplifies complex data.
• Helps identify trends and patterns.
• Aids in decision-making processes.
• Enhances data storytelling.
Matplotlib Library
Introduction to Matplotlib
Matplotlib is a widely used plotting library for Python that provides a flexible way to create a variety of
static, animated, and interactive visualizations in Python.
Installation
You can install Matplotlib using pip:
pip install matplotlib
Basic Usage
To use Matplotlib, you typically import the pyplot module:
import [Link] as plt
Different Types of Charts using Pyplot
1. Line Chart
A line chart is used to display information as a series of data points called 'markers' connected by straight
line segments.
Example:
import [Link] as plt
# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
# Create a line chart
[Link](x, y, marker='o')
[Link]("Line Chart Example")
[Link]("X-axis")
[Link]("Y-axis")
[Link]()
[Link]()
2. Bar Chart
A bar chart presents categorical data with rectangular bars. The lengths of the bars are proportional to the
values they represent.
Example:
import [Link] as plt
# Sample data
categories = ['A', 'B', 'C', 'D']
values = [3, 7, 5, 2]
# Create a bar chart
[Link](categories, values, color='skyblue')
[Link]("Bar Chart Example")
[Link]("Categories")
[Link]("Values")
[Link]()
3. Histogram
A histogram is a graphical representation of the distribution of numerical data, showing the number of data
points that fall within a specified range of values (bins).
Example:
import [Link] as plt
import numpy as np
# Generate random data
data = [Link](1000)
# Create a histogram
[Link](data, bins=30, color='purple', alpha=0.7)
[Link]("Frequency")
[Link]()[Link]("Histogram Example")
[Link]("Value")
4. Pie Chart
A pie chart is a circular statistical graphic divided into slices to illustrate numerical proportions.
Example:
import [Link] as plt
# Sample data
labels = ['Python', 'Java', 'C++', 'Ruby']
sizes = [45, 30, 15, 10]
colors = ['gold', 'lightcoral', 'lightskyblue', 'lightgreen']
# Create a pie chart
[Link](sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140)
[Link]("Pie Chart Example")
[Link]('equal') # Equal aspect ratio ensures the pie chart is circular.
[Link]()
Note:
Data Visualization: Essential for interpreting and presenting data effectively.
Matplotlib: A powerful library for creating a wide range of visualizations in Python.
Application of Charts:
• Line Chart: Ideal for displaying trends over time.
• Bar Chart: Suitable for comparing categorical data.
• Histogram: Used for showing frequency distributions.
• Pie Chart: Good for illustrating proportions of a whole.
Example Program:
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in
Python.
import [Link] as plt
# Line chart
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Line Chart')
[Link]()
# Bar chart
[Link](x, y)
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Bar Chart')
[Link]()
# Histogram
data = [1, 2, 3, 4, 5, 2, 3, 1, 4, 5, 3, 2, 1]
[Link](data, bins=5)
[Link]('Value')
[Link]('Frequency')
[Link]('Histogram')
[Link]()
# Pie chart
labels = ['Alice', 'Bob', 'Charlie']
values = [25, 30, 35]
[Link](values, labels=labels, autopct='%1.1f%%')
[Link]('Pie Chart')
[Link]()
Output: