Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

To Create an Application Where You Can Insert Data Into an SQLite Database and View It Using a Treeview in Tkinter

The document outlines the creation of a Tkinter application that interacts with an SQLite database to insert and display user data in a Treeview format. It details the setup of the database, the creation of input fields and buttons for data entry, and the implementation of functions to insert and fetch data. The application allows users to input their name, age, and gender, and view the data in real-time within the Treeview widget.

Uploaded by

MARK SIMIYU
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

To Create an Application Where You Can Insert Data Into an SQLite Database and View It Using a Treeview in Tkinter

The document outlines the creation of a Tkinter application that interacts with an SQLite database to insert and display user data in a Treeview format. It details the setup of the database, the creation of input fields and buttons for data entry, and the implementation of functions to insert and fetch data. The application allows users to input their name, age, and gender, and view the data in real-time within the Treeview widget.

Uploaded by

MARK SIMIYU
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

To create an application where you can insert data into an SQLite database and view it using

a Treeview in Tkinter, we will break the process down step by step.

Overview

We'll be creating:

1. SQLite database: We'll create a database to store the data.


2. Tkinter Widgets: We'll use various Tkinter widgets to input data, submit it to the
database, and display it in a Treeview.
3. Treeview Widget: This will display the data fetched from the SQLite database in a
tabular format.

Step-by-Step Breakdown

1. Setting up SQLite: We will first create a SQLite database and a table.


2. Creating Tkinter Widgets: We will create input fields for data entry, a button to
submit the data, and a Treeview to display the data.
3. Fetching Data: We will retrieve data from the database and display it in the
Treeview.

Code Implementation
python
Copy code
import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3

# SQLite Database Setup


connection = sqlite3.connect("userdata.db") # Connect to SQLite database
cursor = connection.cursor()

# Create a table if it doesn't already exist


cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER NOT NULL,
gender TEXT NOT NULL
)
""")
connection.commit() # Commit changes

# Function to Insert Data into the Database


def insert_user():
name = name_entry.get() # Retrieve text from Name entry
age = age_entry.get() # Retrieve text from Age entry
gender = gender_var.get() # Retrieve selected value from gender
options

if not name or not age or not gender:


messagebox.showwarning("Input Error", "Please fill all fields.")
return
try:
# Convert age to integer
age = int(age)
cursor.execute("INSERT INTO users (name, age, gender) VALUES (?, ?,
?)", (name, age, gender))
connection.commit()
messagebox.showinfo("Success", "User added successfully!")
name_entry.delete(0, tk.END) # Clear name entry
age_entry.delete(0, tk.END) # Clear age entry
gender_var.set("") # Clear gender selection
refresh_treeview() # Refresh Treeview to show updated data
except ValueError:
messagebox.showwarning("Input Error", "Age must be a number.")

# Function to fetch users and refresh the Treeview


def refresh_treeview():
# Clear the existing Treeview entries
for row in tree.get_children():
tree.delete(row)

# Fetch all users from the database


cursor.execute("SELECT * FROM users")
users = cursor.fetchall()

# Insert each user into the Treeview


for user in users:
tree.insert("", "end", iid=user[0], text=user[0], values=(user[1],
user[2], user[3]))

# Tkinter GUI Setup


root = tk.Tk()
root.title("SQLite Data Insertion with Treeview")

# Create Label and Entry for Name


tk.Label(root, text="Name:").grid(row=0, column=0, padx=10, pady=5)
name_entry = tk.Entry(root)
name_entry.grid(row=0, column=1, padx=10, pady=5)

# Create Label and Entry for Age


tk.Label(root, text="Age:").grid(row=1, column=0, padx=10, pady=5)
age_entry = tk.Entry(root)
age_entry.grid(row=1, column=1, padx=10, pady=5)

# Create Label and Radiobuttons for Gender


tk.Label(root, text="Gender:").grid(row=2, column=0, padx=10, pady=5)
gender_var = tk.StringVar()

gender_male = tk.Radiobutton(root, text="Male", variable=gender_var,


value="Male")
gender_female = tk.Radiobutton(root, text="Female", variable=gender_var,
value="Female")

gender_male.grid(row=2, column=1, padx=10, pady=5, sticky="w")


gender_female.grid(row=2, column=1, padx=10, pady=5, sticky="e")

# Create a Button to Add User


add_button = tk.Button(root, text="Add User", command=insert_user)
add_button.grid(row=3, column=0, columnspan=2, pady=10)

# Create Treeview to display data


tree = ttk.Treeview(root, columns=("Name", "Age", "Gender"),
show="headings")
tree.heading("Name", text="Name")
tree.heading("Age", text="Age")
tree.heading("Gender", text="Gender")
tree.grid(row=4, column=0, columnspan=2, pady=10, padx=10)

# Refresh Treeview on startup to display data from the database


refresh_treeview()

# Run the Tkinter event loop


root.mainloop()

# Close the database connection when done


connection.close()

Explanation of the Code:

1. SQLite Database Setup:

 We start by connecting to the SQLite database using


sqlite3.connect("userdata.db"). If the database doesn’t exist, SQLite will create
it automatically.
 We then execute a SQL command to create the users table with columns id, name,
age, and gender. If the table already exists, no new table will be created.
 The commit() function ensures that the changes are saved in the database.

2. Tkinter Widgets:

 Label:
o Labels are used to display text. They help in guiding users by labeling input
fields.
o tk.Label(root, text="Name:") creates a label with the text "Name:".
 Entry:
o Entry widgets allow the user to input text.
o name_entry = tk.Entry(root) creates an entry field for the user to type
their name.
 Radiobutton:
o Radiobuttons are used for selecting one option from a group. Here, we use two
radio buttons for the user to choose between "Male" and "Female" for gender.
o gender_var is a StringVar that holds the selected gender value.
o gender_male = tk.Radiobutton(root, text="Male",
variable=gender_var, value="Male") creates the Male option, and
similarly, we create the Female option.
 Button:
o A button is created with tk.Button() to trigger the insertion of user data into
the database. The command=insert_user binds the function insert_user to
the button's click event.

3. Treeview Widget:

 A Treeview widget is used to display tabular data.


o tree = ttk.Treeview(root, columns=("Name", "Age", "Gender"),
show="headings") creates a treeview widget with three columns for
displaying the name, age, and gender of users.
o show="headings" ensures that the treeview only displays the columns
without showing the default tree structure (like an extra column for item ID).
o tree.heading("Name", text="Name") sets the header for the Name
column.

4. Insert Data:

 When the user clicks the "Add User" button, the insert_user function is triggered.
o It retrieves data from the name_entry, age_entry, and gender_var fields.
o If the input is valid (name, age, and gender are provided), the data is inserted
into the users table using an INSERT INTO SQL command.
o After inserting, the fields are cleared, and the Treeview is refreshed to display
the updated data.

5. Refresh Treeview:

 The refresh_treeview function fetches all users from the database using SELECT *
FROM users and inserts them into the Treeview.
 tree.insert("", "end", iid=user[0], text=user[0], values=(user[1],
user[2], user[3])) inserts a row into the Treeview for each user retrieved from the
database.

Step-by-Step GUI Layout:

1. Name, Age, Gender: The labels and corresponding entry fields (for text input) and
radio buttons (for gender selection) are placed in a grid layout.
2. Add User Button: Below the entry fields, a button is created to trigger the insertion
of data into the database.
3. Treeview: Below the button, the Treeview widget is placed to display the inserted
data in a tabular format.

Running the Application:

 When the application starts, it loads the Tkinter window and displays the widgets.
 Users can input their name, age, and gender, then click "Add User" to insert the data
into the SQLite database.
 The data is displayed in the Treeview in real-time.

Conclusion:

This example demonstrates how to create a Tkinter-based CRUD application with SQLite for
inserting data and viewing it using a Treeview widget. We used basic Tkinter widgets like
Label, Entry, Radiobutton, Button, and Treeview to create a user-friendly interface. The
data is stored and retrieved from an SQLite database, allowing users to see the updated
records dynamically.

You might also like