Unit -5
Contents
Introduction to tkinter
Top Level Windows
Dialogs, Message and Entry
Event Handling, Menus
Listboxes and Scrollbars, Text
Canvas, Grids
SQL Database interfaces with SQLite3 : Basic operations
SQLite functions
SQLite Interfaces
Object Relational mappers
Table load scripts
Introduction to Tkinter
Importing Tkinker Modules
• Python provides the standard library Tkinter for
creating the graphical user interface for
desktop based applications.
Creating the main window for
• An empty Tkinter top-level window can be GUI app
created by using the following steps :
1. import the Tkinter module.
2. Create the main application window.
Adding widgets to the app
3. Add the widgets like labels, buttons,
frames, etc. to the window.
4. Call the main event loop so that the actions
can take place on the user's computer Enter the main event Loop
screen.
Other libraries for creating
GUI
Kivy
Python Qt
wxPython
Introduction to Tkinter
Widgets in Tkinter Widgets Description
are the elements of Label display text or image on the screen
Button add buttons to your application
GUI application which Canvas draw pictures and others layouts like texts, graphics etc.
provides various ComboBox contains a down arrow to select from list of available options
controls, such as : CheckButton displays a number of options to the user as toggle buttons from which
user can select any number of options.
Labels, RadioButton implement one-of-many selection as it allows only one option to be
Buttons, selected
ComboBoxes, Entry input single line text entry from user
CheckBoxes, Frame container to hold and organize the widgets
MenuBars, Message same as that of label and refers to multi-line and non-editable text
Scale provide a graphical slider which allows to select any value from that
RadioButtons, etc. to scale
users to interact with Scrollbar scroll down the contents. It provides a slide controller.
the application. SpinBox allows the user to select from given set of values
Text allows user to edit multiline text and format it for how to be displayed
Menu used to create all kinds of menu used by an application
Simple Program
import tkinter as tk Standard Attributes
for GUI
window = tk.Tk() • Dimensions
greeting = tk.Label(text="Hello, Tkinter") • Fonts
greeting.pack() • Colors
• Cursors
window.mainloop()
• Anchors
label = tk.Label(text="Hello, Tkinter", • Bitmaps
fg="white", bg="black",
width=10, height=10)
Introduction to Tkinter
A window is an instance of Tkinter’s Tk class. Go ahead and create a new window and assign it to
the variable window:
window = tk.Tk()
When code is executed, a new window pops up on the screen. How it looks depends on your operating
system:
Geometry Management
• The pack() method
This method manages the geometry of widgets in blocks
• The grid() method
This method organizes widgets in a tabular structure
• The place() method
This method organizes the widgets to place them in a specific position
from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=100)
frm.grid()
ttk.Label(frm, text="EKE Students").grid(column=0, row=0)
ttk.Button(frm, text="Go there",
command=root.destroy).grid(column=1, row=0)
root.mainloop()
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()
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()
List boxes, Scrollbars, and Text
widgets
In Tkinter, Listboxes, Scrollbars, and Text widgets are powerful GUI components
used to display and manipulate lists of items, handle scrolling functionality, and
present multi-line text content, respectively.
Listbox Widget:
Purpose: The Listbox widget is used to display a list of items from which users
can select one or more items.
Features: Displays a vertical list of items.
Supports single or multiple item selection (using SINGLE or EXTENDED
selection modes).
Can be populated with items dynamically using the insert method or by
providing a list of items during initialization.
import tkinter as tk
root = tk.Tk()
listbox = tk.Listbox(root)
listbox.pack()
# Add items to the listbox
for item in ['Apple', 'Banana', 'Cherry', 'Date']:
listbox.insert(tk.END, item)
root.mainloop()
Scrollbar Widget:
Purpose: The Scrollbar widget is used to add scrolling functionality to
widgets that display more content than can fit in their visible area.
Features:
Provides vertical or horizontal scrolling depending on the orientation
(tk.VERTICAL or tk.HORIZONTAL).
Can be attached to other widgets like Listbox, Text, Canvas, etc., to
enable scrolling through their content.
Example (Vertical Scrollbar for
Listbox)
scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
listbox.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=listbox.yview)
Text Widget:
Purpose:
The Text widget is used to display and edit multi-line text content with
advanced text formatting capabilities.
Features:
Supports multiple lines of text, including rich text formatting such as fonts,
colors, styles, and embedded images.
Provides built-in methods for text manipulation, search and replace, and
clipboard operations.
Can be configured for read-only mode or editable mode
text_widget = tk.Text(root, height=10, width=40)
text_widget.pack()
# Insert text into the Text widget
text_widget.insert(tk.END, "Hello, this is a Text widget.")
root.mainloop()
Scrollbar with Text Widget:
Usage:
When using a Text widget to display large amounts of text,
it's common to pair it with a scrollbar for scrolling through
the text.
Example (Vertical Scrollbar for Text Widget)
scrollbar = tk.Scrollbar(root, orient=tk.VERTICAL)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
text_widget.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text_widget.yview)
Combining these widgets, interactive user interfaces with list-based
selections, scrolling capabilities for handling large content, and multi-
line text editing/display functionalities in Tkinter applications can be
created
Canvas widget and grid layout
manager
In Tkinter, the Canvas widget and grid layout manager are powerful tools for creating
complex graphical user interfaces (GUIs) with customizable graphics and arranging
widgets in a grid-like structure.
Canvas Widget:
Purpose:
The Canvas widget serves as a drawing surface that allows you to create and manipulate
graphical elements such as lines, shapes, text, images, and even custom widgets.
Features:
Supports drawing various shapes like lines, rectangles, ovals, polygons, arcs, and curves.
Allows adding text with different fonts, sizes, colors, and styles onto the canvas.
Enables placement of images (e.g., GIF, JPEG, PNG) on the canvas.
Offers event handling for mouse clicks, movements, keyboard input, and custom
events.Example (Creating a Canvas and Drawing Shapes)
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=300)
canvas.pack()
# Draw a rectangle
canvas.create_rectangle(50, 50, 200, 150, fill='blue')
# Draw an oval
canvas.create_oval(250, 50, 350, 150, fill='green')
root.mainloop()
Grid Layout Manager:
Purpose:
The grid layout manager organizes widgets in a grid-like fashion, allowing
precise control over their placement and alignment within a parent
container (e.g., a window or frame).
Features:Divides the parent container into rows and columns, where
widgets are placed at specific row and column coordinates.
Widgets can span multiple rows or columns, providing flexibility in layout
design.
Supports fine-tuning widget placement using options like rowspan,
columnspan, sticky, padx, pady, and ipadx.
Example (Using Grid Layout)
import tkinter as tk
root = tk.Tk()
label1 = tk.Label(root, text="First Name:")
label2 = tk.Label(root, text="Last Name:")
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
label1.grid(row=0, column=0, padx=10, pady=5, sticky=tk.E)
entry1.grid(row=0, column=1, padx=10, pady=5)
label2.grid(row=1, column=0, padx=10, pady=5, sticky=tk.E)
entry2.grid(row=1, column=1, padx=10, pady=5)
root.mainloop()
Combining Canvas and Grid Layout:
Usage: Canvas widget with the grid layout manager can be combined to create advanced GUIs with
graphical elements arranged in a grid.
Example (Canvas and Widgets in a Grid Layout)
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root, width=400, height=300)
canvas.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
label1 = tk.Label(root, text="Label 1:")
label2 = tk.Label(root, text="Label 2:")
entry1 = tk.Entry(root)
entry2 = tk.Entry(root)
label1.grid(row=1, column=0, padx=10, pady=5, sticky=tk.E)
entry1.grid(row=1, column=1, padx=10, pady=5)
label2.grid(row=2, column=0, padx=10, pady=5, sticky=tk.E)
entry2.grid(row=2, column=1, padx=10, pady=5)
In summary, the Canvas widget allows to create and manipulate
graphics on a Tkinter window, while the grid layout manager provides a
structured way to organize widgets within the window in a grid-like
fashion.
Combining these components enables you to build sophisticated and
visually appealing GUI applications in Python with Tkinter.
SQLite3
SQLite3 is a lightweight and self-contained SQL database engine that's easy to use.
Databases offer numerous functionalities by which one can manage large amounts of
information easily over the web and high-volume data input and output over a typical file
such as a text file.
SQL is a query language and is very popular in databases.
Many websites use MySQL.
SQLite is a “light” version that works over syntax very much similar to SQL.
SQLite is a self-contained, high-reliability, embedded, full-featured, public-domain, SQL
database engine.
It is the most used database engine on the world wide web.
Python has a library to access SQLite databases, called sqlite3, intended for working with
this database which has been included with Python package since version 2.5.
SQLite3 Features
SQLite has the following features.
1.Serverless
2.Self-Contained
3.Zero-Configuration
4.Transactional
5.Single-Database
Serverless
Generally, an RDBMS such as MySQL, PostgreSQL, etc.,
needs a separate server process to operate.
The applications that want to access the database server
use TCP/IP protocol to send and receive requests and it is
called client/server architecture.
SQLite does not require a server to run. SQLite database
is joined with the application that accesses the database.
SQLite database read and write directly from the
database files stored on disk and applications interact
with that SQLite database.
Self-Contained
• SQLite is self-contained means it does not need any external dependencies
like an operating system or external library.
• This feature of SQLite help especially in embedded devices like iPhones,
Android phones, game consoles, handheld media players, etc. SQLite is
developed using ANSI-C.
• The source code is available as a big sqlite3.c and its header file sqlite3.h. If
users want to develop an application that uses SQLite, users just need to
drop these files into your project and compile it with your code.
Zero-Configuration
• SQLite is zero-configuration means no setup or administration needed.
Because of the serverless architecture, you don’t need to “install” SQLite
before using it.
• There is no server process that needs to be configured, started, and stopped.
Transactional
SQLite is Transactional means they are atomic, consistent, isolated, and
durable(ACID).
All transactions in SQLite are fully ACID-compliant.
In other words, all changes within a transaction take place completely or not at
all even when an unexpected situation like application crash, power failure, or
operating system crash occurs.
Single-Database
SQLite is a single database that means it allows a single database connection to
access multiple database files simultaneously.
These features bring many nice features like joining tables in different
databases or copying data between databases in a single command.
SQLite also uses dynamic types for tables. It means you can store any value in
any column, regardless of the data type.
Python SQLite is used to demonstrate how to develop Python database
applications with the SQLite database.
SQLite comes built-in with most of the computers and mobile devices
and browsers.
Python’s official sqlite3 module helps us to work with the SQLite
database.
Basic operations
Connecting to a Database:
import sqlite3
Connect to a SQLite database (will create it if it doesn't exist)
conn = sqlite3.connect('example.db')
Creating a Table:
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# SQL command to create a table
create_table_query = '''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
);
'''
# Execute the SQL command
cursor.execute(create_table_query)
# Commit changes to the database
conn.commit()
Inserting Data:
# Insert data into the table
insert_query = '''
INSERT INTO users (name, age) VALUES (?, ?);
'''
# Data to be inserted
user_data = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
# Execute the insert command for each data entry
cursor.executemany(insert_query, user_data)
# Commit changes
conn.commit()
Fetching Data:
# Fetch data from the table
fetch_query = '''
SELECT * FROM users;
'''
# Execute the fetch command
cursor.execute(fetch_query)
# Fetch all rows
rows = cursor.fetchall()
# Print the fetched data
for row in rows:
print(row)
Updating Data:
# Update data in the table
update_query = '''
UPDATE users SET age = ? WHERE name = ?;
'''
# New data
new_data = [(32, 'Alice'), (26, 'Bob')]
# Execute the update command for each data entry
cursor.executemany(update_query, new_data)
# Commit changes
conn.commit()
Deleting Data:
# Delete data from the table
delete_query = '''
DELETE FROM users WHERE name = ?;
'''
# Data to be deleted
delete_data = ('Charlie',)
# Execute the delete command
cursor.execute(delete_query, delete_data)
# Commit changes
conn.commit()
Closing the Connection:
# Close the cursor and connection
cursor.close()
conn.close()
SQLite functions are built-in functions provided by the SQLite database
engine that allow you to perform various operations on data within your
SQL queries.
These functions can be used in SELECT statements, WHERE clauses,
UPDATE statements, and other SQL commands to manipulate data or
perform calculations.
Aggregate Functions:
• SUM(column): Calculates the sum of values in the specified
column.
• AVG(column): Calculates the average of values in the specified
column.
• COUNT(column): Counts the number of rows or non-null values
in the specified column.
• MAX(column): Finds the maximum value in the specified column.
• MIN(column): Finds the minimum value in the specified column.
SELECT SUM(sales) AS total_sales FROM transactions;
String Functions:
• LENGTH(string): Returns the length of the string.
• UPPER(string): Converts the string to uppercase.
• LOWER(string): Converts the string to lowercase.
• SUBSTR(string, start, length): Extracts a substring
from the string.
• REPLACE(string, old_text, new_text): Replaces
occurrences of old_text with new_text in the string.
SELECT UPPER(name) AS uppercase_name FROM users;
Date and Time Functions:
• DATE(column): Extracts the date part from a datetime
value.
• TIME(column): Extracts the time part from a datetime
value.
• DATETIME('now'): Returns the current date and time.
• strftime(format, column): Formats date and time
values according to the specified format.
Example:
SELECT DATE(order_date) AS order_date_only FROM orders;
Mathematical Functions:
• ABS(number): Returns the absolute value of a number.
• ROUND(number, decimal_places): Rounds a number
to the specified decimal places.
• RANDOM(): Generates a random integer between 0 and
1.
• SQRT(number): Calculates the square root of a number.
Example:
SELECT ROUND(price * 1.1, 2) AS new_price FROM products;
Conditional Functions:
• IFNULL(expression, default_value): Returns
expression if not null, otherwise returns default_value.
• COALESCE(value1, value2, ...): Returns the first non-
null value from the list of arguments.
SELECT COALESCE(sales_target, 0) AS actual_sales FROM sales_data;
They are powerful tools that allow you to manipulate and
transform data directly within your SQL queries, making
your database operations more efficient and flexible.
SQLite interfaces
SQLite interfaces refer to the various ways that can interact with SQLite databases, both in terms of
programming languages and tools.
Here are explanations of different SQLite interfaces:
SQLite Command-Line Interface (CLI):The SQLite CLI is a command-line tool that allows direct
interaction with SQLite databases without the need for programming.
Can create, modify, query, and manage SQLite databases using SQL commands directly in the
command line.
It's useful for quick database operations, testing SQL queries, and managing SQLite databases
without relying on external applications.
SQLite3 Python Module:
The sqlite3 module in Python provides an interface to interact with SQLite databases
programmatically.
It allows to create SQLite database connections, execute SQL commands, fetch data, and manage
transactions within Python scripts.
Can perform operations like creating tables, inserting data, querying data, updating records, and
deleting data using the SQLite3 module.
SQLite APIs in Other Programming Languages:
Besides Python, many programming languages offer SQLite APIs that allow you to
work with SQLite databases.
For example:
C/C++: SQLite provides a C API (sqlite3.h) for C/C++ developers to integrate SQLite
into their applications.
Java: There are Java libraries like JDBC and SQLiteJDBC that provide SQLite interfaces
for Java applications.
C#/.NET: The System.Data.SQLite library offers SQLite support for .NET applications
through ADO.NET interfaces.
PHP: PHP has PDO (PHP Data Objects) and SQLite3 extensions for interacting with
SQLite databases.SQLite Browser/Manager Tools:
SQLite GUI tools such as "SQLite Browser," "DB Browser for SQLite," or "SQLite
Manager" provide graphical interfaces for managing SQLite databases.
These tools allow you to visually create and modify database schemas, execute SQL
queries, import/export data, and view database structures.
Mobile App Development Interfaces:SQLite is commonly used in mobile app
development, especially for Android and iOS applications.
Mobile development frameworks like Android Studio for Android or Xcode for
iOS provide interfaces and APIs to integrate SQLite databases into mobile apps.
Libraries and frameworks such as Room Persistence Library (Android) or
CoreData (iOS) simplify SQLite database operations for mobile developers.
Web Development Interfaces:SQLite can be used in web development,
particularly for small-scale applications or prototyping.Web development
frameworks like Django (Python), Laravel (PHP), or Express (Node.js) often have
integrations or plugins for SQLite databases.
ORM (Object-Relational Mapping) libraries like SQLAlchemy (Python) or
Sequelize (Node.js) abstract database interactions, including SQLite, for web
applications.
These SQLite interfaces cater to different use cases and developer preferences,
providing flexibility and ease of use when working with SQLite databases across
various platforms and programming languages.
Object Relational Mappers
Object-Relational Mappers (ORMs) are tools or libraries that bridge the
gap between the object-oriented programming (OOP) paradigm and
relational databases.
They provide a way to work with databases using high-level
programming constructs like classes and objects, instead of directly
dealing with SQL queries and database tables.
Mapping Objects to Tables:
ORM frameworks map classes in your codebase to tables in the database. Each instance of a
class corresponds to a row in the table, and class attributes map to columns in the table.
This mapping is typically defined using annotations, configuration files, or code conventions.
Example (Python SQLAlchemy):
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)
engine = create_engine('sqlite:///example.db')
Base.metadata.create_all(engine)
Querying Data with Objects:
ORM frameworks allow you to query data from the database using object-oriented
syntax. Instead of writing raw SQL queries, you use methods and properties provided
by the ORM to fetch, filter, and manipulate data.
Example (Python SQLAlchemy Querying):
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()
# Query all users
users = session.query(User).all()
# Filter users by age
young_users = session.query(User).filter(User.age < 30).all()
Relationships and Associations:
ORMs handle relationships between database tables using object relationships. For example,
in a one-to-many relationship, one object can have multiple related objects, and vice versa.
ORMs define these relationships using attributes like relationship or ForeignKey.Example
(Python SQLAlchemy Relationships):
from sqlalchemy.orm import relationship
class Address(Base):
__tablename__ = 'addresses'
id = Column(Integer, primary_key=True)
street = Column(String)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship("User", back_populates="addresses")
User.addresses = relationship("Address", back_populates="user")
Automatic Schema Generation and Migration:
ORMs often provide tools to automatically generate database schemas
based on your class definitions (create_all() in SQLAlchemy) and handle
schema migrations when your class definitions change (alembic in
SQLAlchemy).
Database Agnostic:ORMs abstract away database-specific SQL syntax,
making your codebase more portable across different database
management systems (DBMS) such as SQLite, PostgreSQL, MySQL, etc.
The ORM framework handles the translation of object-oriented queries to
the appropriate SQL dialect for the DBMS in use.
ORMs are popular in modern software development because they
streamline database interactions, reduce boilerplate code, improve code
readability, and facilitate rapid application development by allowing
developers to work with databases in a more intuitive, object-oriented
manner.
Table load scripts, also known as data loading scripts or import scripts, are scripts
designed to populate database tables with initial or external data.
These scripts are commonly used during the setup phase of a database application
or when importing data from external sources into an existing database.
Here's an explanation of table load scripts and their typical characteristics:
Purpose:
Initial Data Population: Table load scripts are often used to populate database
tables with initial data required for the application to function correctly.
This includes default settings, reference data, or seed data necessary for
application functionality.
Data Import from External Sources: Load scripts can also be used to import data
from external sources such as CSV files, Excel spreadsheets, JSON files, or other
databases.
This is common when migrating data from legacy systems or integrating data from
third-party sources.
Script Structure:
Data Source Specification: Load scripts typically specify the source of data, such as a file path or a
database connection string, depending on whether the data is coming from an external file or another
database.
Data Transformation (Optional): In some cases, data may need to be transformed or formatted before
being loaded into the database.
Load scripts can include data transformation logic such as data cleaning, normalization, or data type
conversion.
SQL Statements:
The core of a table load script consists of SQL statements that insert or update data in the target
database tables.
These SQL statements may include INSERT, UPDATE, DELETE, or MERGE statements depending on the
data loading strategy.
Data Loading Strategies:Bulk Loading: For large datasets, bulk loading techniques like using COPY
(PostgreSQL), LOAD DATA INFILE (MySQL), or BULK INSERT (SQL Server) may be employed to optimize
data loading performance.
Transactional Loading: Load scripts may be designed to execute within a transaction to ensure data
consistency and rollback in case of errors during the loading process.
Transactions help maintain data integrity during large-scale data imports.
Error Handling and Logging:
Error Handling: Load scripts often include error handling mechanisms to capture and handle data
loading errors.
This may involve logging error messages, skipping erroneous records, or retrying failed operations.
Logging:
Load scripts may log information about the data loading process, including the number of records
processed, success/failure status, timestamps, and any relevant metrics or statistics.
Automation and Scheduled Execution:
Automation: Load scripts are frequently automated to run as part of a deployment process or
scheduled job.
Automation tools or job schedulers can be used to execute load scripts at predefined intervals or in
response to specific events.
Scheduled Execution:
Scheduled execution ensures that data is regularly updated or refreshed in the database, especially
for data sources that change frequently or require periodic updates.
Overall, table load scripts play a crucial role in setting up and maintaining database systems by
efficiently loading data into database tables from various sources while ensuring data accuracy,
integrity, and consistency.