Step by Step Tutorial for Beginners: Building a GUI App using Tkinter and SQLite with Python

Posted by


In this tutorial, we will walk through how to create a GUI app using Tkinter and SQLite in Python. Tkinter is the standard GUI toolkit for Python and SQLite is a lightweight, embedded database that is perfect for small applications. By combining these two tools, we can create a powerful and user-friendly application that stores data in a database.

Step 1: Install Tkinter and SQLite
Before we can start building our GUI app, we need to make sure that we have Tkinter and SQLite installed. Tkinter comes pre-installed with Python, so you should have it already. To install SQLite, you can use pip by running the following command in your terminal:

pip install sqlite3

Step 2: Set up the GUI Interface
Now that we have the necessary tools installed, let’s start by setting up the GUI interface for our application. Create a new Python file and import the necessary libraries:

import tkinter as tk
from tkinter import messagebox
import sqlite3

Next, let’s create a root window and add some basic elements to our interface:

root = tk.Tk()
root.title("Simple SQLite App")

label = tk.Label(root, text="Enter your data:")
label.pack()

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root, text="Save", command=save_data)
button.pack()

root.mainloop()

Step 3: Connect to the SQLite Database
Now that we have set up the GUI interface, let’s create a connection to our SQLite database. We will create a new database file called "data.db" and a table called "users" with two columns, "id" and "data":

conn = sqlite3.connect('data.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, data TEXT)''')

Step 4: Define Functions to Save and Retrieve Data
Next, let’s define the function that will save the data entered by the user into the SQLite database:

def save_data():
    data = entry.get()
    if data:
        c.execute("INSERT INTO users (data) VALUES (?)", (data,))
        conn.commit()
        messagebox.showinfo("Success", "Data saved successfully!")
    else:
        messagebox.showerror("Error", "Please enter some data.")

We also need a function to retrieve the data from the database and display it in a messagebox:

def show_data():
    c.execute("SELECT * FROM users")
    data = c.fetchall()
    if data:
        messagebox.showinfo("Data", data)
    else:
        messagebox.showinfo("Info", "No data found.")

Step 5: Add a Button to Retrieve Data
Finally, let’s add a button to our GUI interface that will trigger the show_data function to retrieve and display the data from the SQLite database:

show_button = tk.Button(root, text="Show Data", command=show_data)
show_button.pack()

Step 6: Run the Application
Now that we have completed all the steps, save your file and run the application by executing the Python script. You should see a simple GUI interface with an entry field to save data, a button to save the data to the database, and a button to retrieve and display the data stored in the database.

That’s it! You have successfully created a GUI application using Tkinter and SQLite in Python. With this basic example, you can now expand and customize your application to suit your needs and add more advanced features. Happy coding!

0 0 votes
Article Rating

Leave a Reply

32 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@justiccoolman1816
2 hours ago

You are very sympathic and you have a talent for clear explanations,,
but i think it would be better to teach sql from the beginning like it is meant to be.
Sql is an relational database what means you would structure that case differently:
Only two table are needed: The first table (name: Recipies) holds an id and name (recipiename) column. The second table (name Ingridients) holds following columns: another id, Recipies_Fk (foreign key, pointer to the id column of the first tabel) and then all the ingridient fields. Thats it. Now the table name of your sql statements are static. But you need now more sql statments: "Select * from Recipies" select a random line in the pyhton code and pass the id to the follwoing statement "Select * from Ingriedients where Recipies_Fk = <An Id of your Recipie Table>;".

You also gain there big advantage which is that you are only loading the neccessary ingridients.

@gulrukh1386
2 hours ago

Hi, Mariya,
you are wonderful,
your laughing is wonderful

@_24KJayy
2 hours ago

I want to say thank you very much I just got it with your teaching you made it so simple for me & understandable , i learned more in this video of yours than I have in alot of videos put together thank you so much

@shanecrawley4050
2 hours ago

full error is File "C:UsersFamilyDocumentsCodingrecipe pickerrecipepicker.venvLibsite-packagesPILImageTk.py", line 132, in _del_

name = self.__photo.name

^^^^^^^^^^^^

AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

@shanecrawley4050
2 hours ago

name = self.__photo.name

^^^^^^^^^^^^

AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

@davidcollins6976
2 hours ago

Very good tutorial!
Some recipes have ingredients listed as "4 of egg" or "of salt"
Coconut Flapjacks have "2 1/2 1/2 of coconut"
What can we do to address these problems?
Thanks!

@robynrox
2 hours ago

Thank you so much! Not only did you effectively demonstrate the process, you made it fun!

@warrenslittleworld1387
2 hours ago

This is late but with python to load PNG images all you need is tkinter.PhotoImage(file="./img.png") no pillow needed. I don't even have anything extra installed I only use standard programing.

@rnpk9572
2 hours ago

Forget about the tutorial let me say you are really beautiful with due respect. 😍

@geee7672
2 hours ago

Hi, I work in Photoshop and Adobe Illustrator, I have a plan to make a GUI that I want to customise (automate) my tasks. I am in flexographics and Frontend web. Can we have a private discusion, I send you a dummy project to be done in TKinter. You send me a quote for that automation project and the following prototypes will be discussed later. I would appreciate if we discuss this tomorrow.

@superhacker1569
2 hours ago

why using root.geometry is a bad method

i always use it in my projects

root.update()
sw=root.winfo_screenwidth()
sh=root.winfo_screenheight()
fw=root.winfo_width()
fh=root.winfo_height()
w=(sw-fw)//2
h=(sh-fh)//2
root.geometry("%sx%s+%s+%s"%(fw,fh,w,h)

note:
geometry method can be dynamic depending on the content inside

@dyno2647
2 hours ago

Are you any chance related to networkchuck

@shripop1424
2 hours ago

Hi Mariya ! Very nice. Helped me a lot to develop for MySQL application. Thanks.

@doodo7381
2 hours ago

When I want to make a gui tkinter project and also with SQLite3 the first youtube channel your channel will the first recommended channel in my mind

@geee7672
2 hours ago

…Hi I wanna follow your page. Tomorrow I will analyse what you teach. But what id happening online, especilly with"so called Python experts", they are wasting peoples time with basic stuff, same videos and not complete projects. I have been analysing their YouTube scams and if people have been paying them, I can never say enough sorries. Kevin Powell sets the trend in teaching HTML. I have targets and projects.

@chimkens
2 hours ago

thank you! When I set the button colors, the application will not show the correct hex color. Why is that?

@timvildanov
2 hours ago

Thanks a lot

@antascii
2 hours ago

At the 10 minute mark of the video, when I try to run the app, I get an error message in the terminal.
All the image files and font files etc are in the same directory as my source code file (including RRecipe_logo.png) !
I've checked my syntax against yours and even downloaded your completed recipePicker.py and tried to run it but I get the same error message at runtime, so I don't think it's a syntax error.
I think that this line of code is where the error is being generated: logo_img = ImageTk.PhotoImage(file = "RRecipe_logo.png")
FYI: I'm using Visual Studio Code as my IDE.
Here's the error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Coding\Python Source\General Py Code Files\RRecipe_logo.png'

Exception ignored in: <function PhotoImage._del_ at 0x000001D50B401440>

Traceback (most recent call last):

File "C:UsersOperatorAppDataLocalProgramsPythonPython312Libsite-packagesPILImageTk.py", line 132, in _del_

name = self.__photo.name

^^^^^^^^^^^^

AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

@danielx40
2 hours ago

Finally, someone talks like a real person, instead of with those "programmer voice" like in most online tutorials.

@stephenehler262
2 hours ago

Best Pancake recipe ever!

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