How to Load Data from MySQL Database into Tkinter TreeView using Python
In this python Tutorial we will learn How To retrieve data from a MySQL database and display it in a Tkinter TreeView using Python.
The TreeView widget provides an organized and hierarchical way to present data in a tabular format, making it ideal for displaying database records.
Project Source Code:
import tkinter as tkfrom tkinter import *from tkinter import ttkimport mysql.connectorconnection = mysql.connector.connect(host='localhost', user='root', port='3306',password='', database='test_py')c = connection.cursor()root = Tk()frame = tk.Frame(root, padx=40,pady=40, bg='grey')c.execute("SELECT firstname FROM `users_2`")options = c.fetchall()selected = StringVar(frame)selected.set(options[0])combobox = ttk.Combobox(frame, textvariable=selected, values=options,font=('verdana',14))combobox.pack()frame.pack()root.mainloop()Setting up the TreeView: We will create a frame within the main window to hold the TreeView widget. The TreeView will have five columns representing the different fields of our database table: ID, First Name, Last Name, Email, and Age. We will configure the column widths and headings accordingly. Retrieving and Displaying Data: To populate the TreeView, we will define a function named displayData(). Inside this function, we will execute a SQL query to fetch the records from the MySQL database table. We will iterate over the retrieved data and insert each record into the TreeView using the insert() method. Running the Application: Finally, we will call the displayData() function to load the data into the TreeView. We will then start the main event loop using the mainloop() method to display the GUI and interact with the user.OutPut: