How To Fetch Data From Database In Python Tkinter

In this tutorial, we’ll learn how to fetch data from a database using Python and Tkinter. Tkinter is a popular library for creating graphical user interfaces in Python, and we’ll use it in conjunction with the SQLite3 database to store and retrieve information.

Step 1: Setup the Environment

To get started, you will need to have both Python and Tkinter installed on your system. You can install Tkinter using the following command:

Next, create a Python file for your Tkinter application (e.g., app.py) and import the required libraries:

Step 2: Create a Database Connection

Let’s create a connection to an SQLite3 database. SQLite is a lightweight and easy-to-use database management system that stores data in a single file. In this tutorial, we’ll create a new SQLite database called example.db.

Add the following lines of code to your Python file:

If the example.db file does not exist, it will be created automatically.

Step 3: Create a Database Table

Before we can fetch data from the database, we should create a table to store the information. In this tutorial, we’ll create a table called students with columns id, name, and age:

The CREATE TABLE IF NOT EXISTS statement creates a table only if it does not already exist. This is useful for running the script multiple times without creating duplicate tables.

Step 4: Insert Data into the Table

To test fetching data from the database, let’s insert some sample data into the students table:

Don’t forget to add conn.commit() to save the changes to the database.

Step 5: Fetch Data from the Database

Now that we have some data in the table, let’s create a function that fetches it and displays it in the Tkinter window:

This function executes an SQL query to select all rows from the students table, iterates through the fetched rows using a cursor, and prints the data to the console.

Full Code

Here’s the full code for the Python Tkinter application that fetches data from an SQLite3 database:

Output

The output of the code will display the fetched data from the students table in the console:

ID: 1 NAME: Alice AGE: 21
ID: 2 NAME: Bob AGE: 22
ID: 3 NAME: Charles AGE: 23

Conclusion

In this tutorial, we’ve learned how to fetch data from a database using Python and Tkinter. We created an SQLite3 database, inserted some sample data into it, and implemented a function that fetches and displays the data in the Tkinter window.

With this knowledge, you can now build more complex applications that store and retrieve data from databases, making your Python Tkinter applications more useful and dynamic.