Build a Contact Book With Python, PyQt, and SQLite

FREE Online Courses: Transform Your Career – Enroll for Free!

Have you ever wanted to create a contact book application to store and manage your contacts? In this blog post, we will explore how to build a contact book using Python, PyQt, and SQLite.

This project will allow you to store contact information such as names, phone numbers, and email addresses in a database and provide an intuitive user interface for adding, editing, and viewing contacts.

By following this article, you’ll gain hands-on experience in creating a functional desktop application while learning about essential concepts such as GUI development and database integration. Let’s get started and build your own contact book!

A contact book is a digital application used to store and manage contact information. It typically includes features such as adding new contacts, editing existing contacts, and viewing contact details. In our project, we will be using Python, PyQt (a Python binding for the Qt framework), and SQLite (a lightweight database engine) to develop a contact book application. PyQt provides a powerful toolkit for building graphical user interfaces, and SQLite allows us to store and retrieve contact data efficiently.

Topics Covered:

1. Setting up the development environment
2. Designing the user interface with PyQt
3. Creating a SQLite database and table for storing contacts
4. Implementing functionality to add, edit, and view contacts
5. Handling user input and validation
6. Displaying contacts in a table view
7. Searching and filtering contacts
8. Packaging the application for distribution
9. Conclusion

Setting Up the Development Environment:

Before we start building the contact book, we need to set up our development environment. Follow these steps to ensure you have the necessary tools and libraries installed:

1. Install Python: Visit the official Python website at python.org and download the latest version of Python suitable for your operating system.

2. Install PyQt: Open a terminal or command prompt and run the following command to install PyQt: $ pip install pyqt5

3. Install SQLite: SQLite is included with Python by default, so no additional installation is required.

Designing the User Interface with PyQt:

The user interface (UI) is a crucial component of any application. PyQt offers a variety of widgets and layout managers to design intuitive and interactive UIs. In this section, we will use PyQt’s Designer tool to create the UI for our contact book.

Here are the steps involved:

1. Open the PyQt Designer tool.
2. Design the UI by dragging and dropping widgets onto the form.
3. Set appropriate properties for each widget, such as labels and input fields.
4. Save the UI file, which will be used in our Python code to load the UI.

Creating a SQLite Database and Table for Storing Contacts:

To store our contacts, we need a database. SQLite is a lightweight and self-contained database engine that requires no server setup. In this step, we will create a SQLite database file and a table to hold our contact information.

Here’s how to do it using Python and the sqlite3 module:

import sqlite3

# Connect to the database
conn = sqlite3.connect('contacts.db')

# Create a cursor object to execute SQL queries
cursor = conn.cursor()

# Create the contacts table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS contacts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        phone TEXT,
        email TEXT
    )
''')

# Commit the changes and close the connection
conn.commit()
conn.close()

Implementing Functionality to Add, Edit, and View Contacts:

Now that we have our UI and database set up, we can start implementing the core functionality of our contact book. We will write Python code to handle user actions such as adding a new contact, editing an existing contact, and viewing contact details.

Here’s an example of how these functions could be implemented:

# Code example for adding a contact
def add_contact(name, phone, email):
    conn = sqlite3.connect('contacts.db')
    cursor = conn.cursor()
    cursor.execute('''
        INSERT INTO contacts (name, phone, email)
        VALUES (?, ?, ?)
    ''', (name, phone, email))
    conn.commit()
    conn.close()

# Code example for editing a contact
def edit_contact(contact_id, name, phone, email):
    conn = sqlite3.connect('contacts.db')
    cursor = conn.cursor()
    cursor.execute('''
        UPDATE contacts
        SET name = ?, phone = ?, email = ?
        WHERE id = ?
    ''', (name, phone, email, contact_id))
    conn.commit()
    conn.close()

# Code example for viewing contact details
def view_contact(contact_id):
    conn = sqlite3.connect('contacts.db')
    cursor = conn.cursor()
    cursor.execute('''
        SELECT name, phone, email
        FROM contacts
        WHERE id = ?
    ''', (contact_id,))
    contact = cursor.fetchone()
    conn.close()
    return contact

add_contact('John Doe', '1234567890', '[email protected]')
edit_contact(1, 'John Doe', '0987654321', '[email protected]')
contact = view_contact(1)
print(contact)

Output:

(‘John Doe’, ‘0987654321’, ‘[email protected]’)

Handling User Input and Validation:

When working with user input, it’s crucial to validate and sanitize the data to ensure the integrity of our contact book. We can use PyQt’s signals and slots mechanism to connect UI events to validation functions. For example, we can connect the “Save” button’s clicked signal to a function that validates the input fields and then adds or updates the contact accordingly.

Displaying Contacts in a Table View:

To provide an organized and user-friendly view of our contacts, we can use a table view widget provided by PyQt. This widget allows us to display our contact data in a tabular format and supports sorting and filtering. We can populate the table view by querying the contacts from the SQLite database and dynamically updating the table whenever changes are made.

Searching and Filtering Contacts:

To enhance the usability of our contact book, we can implement search and filter functionality. This allows users to quickly find specific contacts based on criteria such as name, phone number, or email address. We can add search fields and connect them to filter functions that update the table view based on the user’s search query.

Deleting Contacts:

Deleting contacts involves removing a selected contact from the database. Here’s an example of how you can implement the functionality:

def delete_contact(contact_id):
    conn = sqlite3.connect('contacts.db')
    cursor = conn.cursor()
    cursor.execute('''
        DELETE FROM contacts
        WHERE id = ?
    ''', (contact_id,))
    print("Contact Deleted Successfully")
    conn.commit()
    conn.close()

Output:

None
Contact Deleted Successfully

In this code snippet, the delete_contact() function takes the contact_id as a parameter and uses an SQL DELETE statement to remove the contact with the specified ID from the database. The changes are then committed to the database, and the connection is closed.

Error Handling:

Error handling is an important aspect of any application to handle unexpected situations and provide meaningful feedback to the user.

Here’s an example of how you can implement error handling in the context of the contacts list application:

def add_contact(name, phone, email):
    try:
        conn = sqlite3.connect('contacts.db')
        cursor = conn.cursor()
        cursor.execute('''
            INSERT INTO contacts (name, phone, email)
            VALUES (?, ?, ?)
        ''', (name, phone, email))
        conn.commit()
        conn.close()
        print("Contact added successfully!")
    except sqlite3.Error as error:
        print("Error adding contact:", error)

In this code snippet, the try-except block is used to catch any potential errors that may occur during the execution of the SQL statement. If an error occurs, it is captured and printed to the console, providing information about the nature of the error. This allows you to handle exceptions gracefully and provide appropriate feedback to the user.

Similarly, you can implement error handling for other operations such as editing a contact or viewing contact details. The key idea is to encapsulate the database operations within a try-except block and handle any potential errors that may arise.

Packaging the Application for Distribution:

Once we have completed the development of our contact book application, we can package it for distribution. This ensures that users can install and run the application on their machines without needing to install Python or any dependencies. Various tools and libraries are available to package Python applications into standalone executables or installers for different platforms.

Conclusion

In this article, we explored how to build a contact book application using Python, PyQt, and SQLite. We covered setting up the development environment, designing the user interface, creating a SQLite database, implementing contact management functionality, and enhancing the application with search and filter capabilities.

By following this article, you’ve gained valuable experience in developing a desktop application and learned about key concepts such as GUI development and database integration. Now you can apply these skills to create your own custom applications or expand upon the contact book project. Happy coding!

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

Leave a Reply

Your email address will not be published. Required fields are marked *