Search code examples
pythontkintersupabase

Tkinter - Create table using database fetched data


I'm learning Python and I want to make a GUI using Tkinter module. I'm reading some articles about usage and now I'm trying to create a simple table that needs to be pupulated from data fetched from a supabase indatnce. I've writed this code but when I try to debug it the application will crash. How I need to fix it to get a table that will show the desired informations? How I add a label for each column?

supabase: Client = create_client(url, key)
#
response = supabase.table('pdvList').select('*').execute()

# Creting application window 
window = Tk()
window.title("Test screen")
window.geometry("300x300")

# Creating table
for r in range(len(response.data)):
    for c in range(15):
        e = Entry(window, width=20, fg='blue', font=('Arial', 16, 'bold'))
        e.grid(row=r, column=c)
        e.insert(END, response.data)


#window.resizable(False, False)
#
frame = ttk.Frame(window, padding=10)
#
frame.grid(row=r, column=c)
#
window.mainloop()

Solution

  • The proper way to show data in form of a table is by using a Treeview widget from tkinter. Setting up a Treeview with tkinter is quite straightforward. I don't know how the data inside response will be accessible, so I am using a mock data here. The example is dynamic, so if you follow the same structure but have different columns OR data, the treeview will also adapt like so:

    from tkinter import *
    from tkinter import ttk
    
    response = [
        {"id": 1, "name": "Afghanistan"},
        {"id": 2, "name": "Albania"},
        {"id": 3, "name": "Algeria"},
    ]
    cols = list(response[0].keys())
    
    root = Tk()
    
    # Create a treeview with columns from `response`
    tree = ttk.Treeview(root, columns=cols, show="headings")
    tree.pack()
    
    # Add columns to treeview
    for col in cols:
        tree.heading(col, text=col)
        tree.column(col, width=100, anchor="center")
    
    for res in response:
        # Insert each item into the treeview
        tree.insert("", "end", values=list(res.values()))
    
    root.mainloop()
    

    Your code might have to change slightly based on how you retrieve the data from response.

    Read more about ttk.Treeview