How to Display SQLite3 Data In TreeView in Python

In this tutorial we will create a Display SQLite3 Data In TreeView using Python. This code will display all the data in the SQLite database to Tkinter TreeView when the user clicks the display button. The code use tkinter module to create a layout and widgets that can call python functions. When a function is called it will immediately populate the Tkinter TreeView with SQLite database by using SQL SELECT query.

We will be using Python because it has a design philosophy that emphasizes code readability. That's why Python is very easy to use especially for beginners who just started programming. It is very easy to learn the syntax emphasizes readability and it can reduce time-consuming in development.

Getting started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Installing SQLite Browser

After you installed Python, we will now then install the SQLite, here's the link for the DB Browser for SQLite http://sqlitebrowser.org/.

Importing Modules

After setting up the installation and the database, run the IDLE and click the file and then the new file. After that, a new window will appear containing a black file this will be the text editor for the python.

Then copy the code that I provided below and paste it inside the IDLE text editor.

  1. from tkinter import*
  2. import tkinter.ttk as ttk
  3. import tkinter.messagebox as tkMessageBox
  4. import connection

Setting up the Main Frame

After importing the modules, we will now then create the main frame for the application. To do that just copy the code below and paste it inside the IDLE text editor.

  1. root = Tk()
  2. root.title("Python - Display SQLite3 Data In TreeView")
  3. screen_width = root.winfo_screenwidth()
  4. screen_height = root.winfo_screenheight()
  5. width = 700
  6. height = 300
  7. x = (screen_width/2) - (width/2)
  8. y = (screen_height/2) - (height/2)
  9. root.geometry('%dx%d+%d+%d' % (width, height, x, y))
  10. root.resizable(0, 0)

Creating the Database Connection

Then after setting up the design we will now create the database function. To do that just simply copy the code below and paste it inside the IDLE text editor, then save it as connection.py.

  1. import sqlite3
  2.  
  3. def Database():
  4. global conn, cursor
  5. conn = sqlite3.connect('db_member.db')
  6. cursor = conn.cursor()
  7. cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, firstname TEXT, lastname TEXT, address TEXT)")

Designing the Layout

After creating the Main Frame we will now add some layout to the application. Just kindly copy the code below and paste it inside the IDLE text editor.

  1. #==================================FRAME==============================================
  2. Top = Frame(root, width=700, height=50, bd=8, relief="raise")
  3. Top.pack(side=TOP)
  4. Button_Group=Frame(root, width=700, height=50)
  5. Button_Group.pack(side=TOP)
  6. Buttons = Frame(Button_Group, width=200, height=50)
  7. Buttons.pack(side=LEFT)
  8. Buttons1 = Frame(Button_Group, width=500, height=50)
  9. Buttons1.pack(side=RIGHT)
  10. Body = Frame(root, width=700, height=300, bd=8, relief="raise")
  11. Body.pack(side=BOTTOM)
  12.  
  13.  
  14. #==================================LABEL WIDGET=======================================
  15. txt_title = Label(Top, width=300, font=('arial', 24), text = "Python - Display SQLite3 Data In TreeView")
  16. txt_title.pack()
  17.  
  18. #==================================BUTTONS WIDGET=====================================
  19. btn_display = Button(Buttons, width=15, text="Display All", command=populateView)
  20. btn_display.pack(side=LEFT)
  21.  
  22.  
  23. #==================================LIST WIDGET========================================
  24. scrollbary = Scrollbar(Body, orient=VERTICAL)
  25. scrollbarx = Scrollbar(Body, orient=HORIZONTAL)
  26. tree = ttk.Treeview(Body, columns=("Firstname", "Lastname", "Address"), selectmode="extended", height=300, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
  27. scrollbary.config(command=tree.yview)
  28. scrollbary.pack(side=RIGHT, fill=Y)
  29. scrollbarx.config(command=tree.xview)
  30. scrollbarx.pack(side=BOTTOM, fill=X)
  31. tree.heading('Firstname', text="Firstname", anchor=W)
  32. tree.heading('Lastname', text="Lastname", anchor=W)
  33. tree.heading('Address', text="Address", anchor=W)
  34. tree.column('#0', stretch=NO, minwidth=0, width=0)
  35. tree.column('#1', stretch=NO, minwidth=0, width=200)
  36. tree.column('#2', stretch=NO, minwidth=0, width=200)
  37. tree.column('#3', stretch=NO, minwidth=0, width=200)
  38. tree.pack()

Creating the Main Function

This is where the code that contains the main funcitions. This code will display all the SQLite data to the tkinter TreeView when the button is clicked. To do that just copy and write these blocks of code.

  1. #==================================METHODS============================================
  2. def populateView():
  3. tree.delete(*tree.get_children())
  4. connection.Database()
  5. connection.cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  6. fetch = connection.cursor.fetchall()
  7. for data in fetch:
  8. tree.insert('', 'end', values=(data[1], data[2], data[3]))
  9. connection.cursor.close()
  10. connection.conn.close()

Initializing the Application

After finishing the function save the application as index.py. This function will run the code and check if the main application is initialized properly. To do that copy the code below and paste it inside the IDLE text editor.
  1. #==================================INITIALIZATION=====================================
  2.  
  3. if __name__ == '__main__':
  4. root.mainloop()

There you have it we just created a Display SQLite3 Data In TreeView Using Python. I hope that this simple tutorial helps you with what you are looking for. For more updates and tutorials just kindly visit this site.

Enjoy Coding!!

Comments

Submitted byAndrew Baxter (not verified)on Tue, 08/09/2022 - 01:35

I get the error: import connection ModuleNotFoundError: No module named 'connection' Any suggestions?
Submitted byvb_pol (not verified)on Sun, 09/24/2023 - 22:38

make sure that u have the connection.py in the same folder. ckeck the provided code sources.

Add new comment