Utilizing Databases in Python GUI Development with Tkinter – Tutorial #19

Posted by


In this tutorial, we will be learning how to use databases with Tkinter in Python. Databases are a powerful tool for storing and retrieving data, and integrating them with Tkinter can enhance the functionality of your GUI application. In this tutorial, we will be using SQLite as our database management system.

SQLite is a lightweight, serverless, self-contained, and zero-configuration SQL database engine. It is perfect for small to medium-sized applications where a traditional client-server database system like MySQL or PostgreSQL may be unnecessary.

To get started, make sure you have Python installed on your system. You can download the latest version of Python from the official website at https://www.python.org/. Additionally, you will need to install the Tkinter library, which comes pre-installed with Python.

Next, we need to install the sqlite3 library, which will allow us to interact with our SQLite database. You can install the sqlite3 library by running the following command in your terminal or command prompt:

pip install sqlite3

Now that we have all the necessary libraries installed, let’s create a simple Tkinter GUI application that interacts with a SQLite database. We will be creating a To-Do list application where users can add and delete tasks from a database.

First, we need to create a SQLite database and a table to store our tasks. You can create a new SQLite database by running the following code in your Python script:

import sqlite3

# Create a new SQLite database
conn = sqlite3.connect('todo.db')

# Create a new table called tasks
conn.execute('''CREATE TABLE IF NOT EXISTS tasks
             (id INTEGER PRIMARY KEY AUTOINCREMENT,
             task TEXT NOT NULL);''')

conn.commit()
conn.close()

This code creates a new SQLite database called "todo.db" and creates a table called "tasks" with two columns: "id" and "task". The "id" column will be an auto-incrementing integer that serves as the primary key, and the "task" column will store the text of each task.

Next, let’s create a Tkinter GUI application that allows users to add and delete tasks from the database.

import tkinter as tk
import sqlite3

# Create a new SQLite database
conn = sqlite3.connect('todo.db')

root = tk.Tk()
root.title("To-Do List")

# Function to add a new task to the database
def add_task():
    task = task_entry.get()
    if task:
        conn.execute("INSERT INTO tasks (task) VALUES (?)", (task,))
        conn.commit()
        update_list()
        task_entry.delete(0, tk.END)

# Function to delete a selected task from the database
def delete_task():
    selected_index = tasks_listbox.curselection()
    if selected_index:
        task_id = tasks_listbox.get(selected_index)[0]
        conn.execute("DELETE FROM tasks WHERE id=?", (task_id,))
        conn.commit()
        update_list()

# Function to update the tasks listbox with the current tasks from the database
def update_list():
    tasks_listbox.delete(0, tk.END)
    cursor = conn.execute("SELECT id, task FROM tasks")
    for row in cursor:
        tasks_listbox.insert(tk.END, row)

# Entry widget to enter a new task
task_entry = tk.Entry(root, width=50)
task_entry.pack()

# Button to add a new task
add_button = tk.Button(root, text="Add Task", command=add_task)
add_button.pack()

# Listbox to display current tasks
tasks_listbox = tk.Listbox(root, width=50)
tasks_listbox.pack()

# Button to delete a selected task
delete_button = tk.Button(root, text="Delete Task", command=delete_task)
delete_button.pack()

# Initialize the tasks listbox with current tasks from the database
update_list()

root.mainloop()

In this code, we create a Tkinter GUI application with an entry widget for users to input new tasks, a button to add tasks to the database, a listbox to display the current tasks, and a button to delete selected tasks.

The add_task() function inserts a new task into the database when the user clicks the "Add Task" button. The delete_task() function deletes the selected task from the database when the user clicks the "Delete Task" button. The update_list() function updates the tasks listbox with the current tasks from the database.

Make sure to replace the database connection code with your database file location.

That’s it! You have now created a simple To-Do list application using Tkinter and SQLite. You can further enhance this application by adding features like editing tasks, sorting tasks, or setting task priorities. Experiment with different Tkinter widgets and SQLite query statements to customize the application to your liking.

I hope you found this tutorial helpful. If you have any questions or run into any issues, feel free to ask for help in the comments section below. Happy coding!

0 0 votes
Article Rating

Leave a Reply

37 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@Codemycom
1 hour ago

▶️ Watch Entire Tkinter Playlist ✅ Subscribe To My YouTube Channel:
http://bit.ly/2UFLKgj http://bit.ly/2IGzvOR
▶️ See More At: ✅ Join My Facebook Group:
https://Codemy.com http://bit.ly/2GFmOBz
▶️ Learn to Code at https://Codemy.com ✅ Buy a Codemy T-Shirt!
Take $30 off with coupon code: youtube1 http://bit.ly/2VC9WUN

@stupidddkiddd
1 hour ago

Is it possible to have a function that creates a database using Python and TKinter GUI? Let's say you have an Entry Field and Button. Then you pass the information from the entry field to the function tied to the Button (i.e. "submit"). The submit function then creates a database with the name of whatever string was passed from the entry field to the submit function. Is this possible?

@four-xdimension2486
1 hour ago

Do I need to learn SQL before I learn database in Tkinter

@ryano699
1 hour ago

hi, im doing this on visual studio and its not working. is any one familiar with this issues and knows how to fix it?. the issue is with the create table section as it does not recognise the command?

@binkyslife
1 hour ago

💯💯💯💯💯

@ashikgrg4356
1 hour ago

Please make a video on "Fetching data from mysql database randomly"

@rithiksaran
1 hour ago

sir, If i create a database in my system for my python app and send copies of my app to other systems, Will the systems connect with the database in my system when a 3rd user saves data in the database?

@ianlevitt6920
1 hour ago

CREATE TABLE IF NOT EXISTS addresses. then no need to comment out the code !

@sameerkhanna2051
1 hour ago

Thanks for this great tutorial

@didierleprince6106
1 hour ago

Un big merci (:

@djha1257
1 hour ago

Walter

@pymust
1 hour ago

We have to do 'pip install pillow' before using PIL.
Anyway I really appreciate your great videoes.

@Lennardish
1 hour ago

Hello John,
With the help of this Sqlite3 tutorial and one video of yours in which to switch between windows, I succeeded to produce a "Menu" window in which two buttons. One button asking for a "def" to add data to a database, and one button, asking for a "def" to query.
I just now have to find out how to make disappear the "menu" window, when I move to the add data window, and how to make the "menu" window reappear by clicking some button in the add window. But. I am thrilled because you showed me the way. Thanks. I continue my quest 🙂 Paul

@pranyajain2529
1 hour ago

is this error-checked?

@xzex2609
1 hour ago

your videos are one of the few bests in YT , Bro code is awsome in detailed but fast learning and you make it as easy as possible i want to knopw how your work are meant to us , i really thank you

@ahmedelsayed3133
1 hour ago

Why do you use "from tkinter import *" instead of just typing "import tkinter"?

@asf196
1 hour ago

Pls tell me what does the database does

@medmabrouki1034
1 hour ago

Sir
I need to get messagebox error if identity already exists in database with aded function

@AbdoAhmed-vn1kt
1 hour ago

What if i want date datatype and want to sort records by date or something?

@Cael901
1 hour ago

Hello I know you have a great tutorial but I encounter some problem that I cannot understand and fixed it. I think i might miss out something very imporant while learning sql. Thank you in advance

Traceback (most recent call last):

File "G:pythonprogrammsProject test.py", line 33, in <module>

c.execute('''CREATE TABLE addresses (

sqlite3.OperationalError: table addresses already exists

37
0
Would love your thoughts, please comment.x
()
x