How to Display Data in a Table using Tkinter

How to Display Data in a Table using Tkinter

Before we start: This Python tutorial is a part of our series of Python Package tutorials. You can find other Tkinter related topics too!

If your Python application works with data, you may want to display it in your UI. The standard method for displaying data in GUI applications is in a table (tabular) format, consisting of rows and columns just like a spreadsheet. Unfortunately, Tkinter does not provide a widget for the creation of a table.

Luckily, there are alternate methods for creating a table to display data in Tkinter. For example, the Entry widget can be coded to display data in a table, and there are also table packages that can be downloaded from the Python Package Index (PyPI) and installed.

Once you decide on a method, a Tkinter table can be used as an interface for one or more related tables contained in a database for persistent or permanent storage.

How to Display Data in a Tkinter Entry Widget Table

Watch the demo in this video or continue scrolling to get the instructions and code snippets.

An Entry widget is typically used to enter or display a single string of text, but it can also be used together with the range() function and for loop to display values in a table of multiple rows and columns.

In this example, the range() function generates a list of numbers which are populated into an Entry widget table of 5 rows and 4 columns arranged in a grid() layout: 

from tkinter import *
rows = []
for i in range(5):
    cols = []
    for j in range(4):
        e = Entry(relief=GROOVE)
        e.grid(row=i, column=j, sticky=NSEW)
        e.insert(END, '%d.%d' % (i, j))
        cols.append(e)
    rows.append(cols)
 mainloop()

How to Display Data in a Tkinter Tksheet Widget Table

Tksheet is a third party package available in PyPI. It provides a Tkinter table widget with many options including a popup (right-click) menu that lets you add and delete rows, edit data in cells,  and undo changes. Row and column coordinates (x:y) are displayed in each cell by default, and can be replaced with other data.

The Tksheet package can be installed in a terminal or command line, by entering:

pip install tksheet

In this example, the range() function generates a list of numbers based on a grid formula of row {ri} and column {cj} coordinates, and then populates the values in a table consisting of 1 row and 4 columns:

import tkinter as tk
import tksheet
top = tk.Tk()
sheet = tksheet.Sheet(top)
sheet.grid()
sheet.set_sheet_data([[f"{ri+cj}" for cj in range(4)] for ri in range(1)])
# table enable choices listed below:
sheet.enable_bindings(("single_select",
                       "row_select",
                       "column_width_resize",
                       "arrowkeys",
                       "right_click_popup_menu",
                       "rc_select",
                       "rc_insert_row",
                       "rc_delete_row",
                       "copy",
                       "cut",
                       "paste",
                       "delete",
                       "undo",
                       "edit_cell"))
top.mainloop()

How to Display SQLite Data in a Tkinter Table

A Tkinter table can serve as an interface for data located in permanent storage, such as an SQLite database. In this case, an SQL statement is typically used to select all or some of the data in one or more database tables for display in the table. For example:

# An SQL statement that selects all data from a table:

SELECT * from <database_table_name>

Note that the data displayed in the Tkinter table is not persistent, but the query statement is saved automatically in the database for future use.

In this example, a Tkinter table is used as an interface to display data in an SQLite database table:

from tkinter import ttk
import tkinter as tk
import sqlite3
def connect():
    con1 = sqlite3.connect("<path/database_name>")
    cur1 = con1.cursor()
    cur1.execute("CREATE TABLE IF NOT EXISTS table1(id INTEGER PRIMARY KEY, First TEXT, Surname TEXT)")
    con1.commit()
    con1.close()
def View():
    con1 = sqlite3.connect("<path/database_name>")
    cur1 = con1.cursor()
    cur1.execute("SELECT * FROM <table_name>")
    rows = cur1.fetchall()    
    for row in rows:
        print(row) 
        tree.insert("", tk.END, values=row)        
    con1.close()
# connect to the database
connect() 
root = tk.Tk()
tree = ttk.Treeview(root, column=("c1", "c2", "c3"), show='headings')
tree.column("#1", anchor=tk.CENTER)
tree.heading("#1", text="ID")
tree.column("#2", anchor=tk.CENTER)
tree.heading("#2", text="FNAME")
tree.column("#3", anchor=tk.CENTER)
tree.heading("#3", text="LNAME")
tree.pack()
button1 = tk.Button(text="Display data", command=View)
button1.pack(pady=10)
root.mainloop()

How to Display Pandas and Numpy Data in a Tkinter Table

In this example, a Pandas and Numpy data structure is displayed in a Tkinter table:

import pandas as pd
import numpy as np
import sys 
from tkinter import * 
root = Tk()
root.geometry('580x250')
dates = pd.date_range('20210101', periods=8)
dframe = pd.DataFrame(np.random.randn(8,4),index=dates,columns=list('ABCD'))
txt = Text(root) 
txt.pack() 
class PrintToTXT(object): 
 def write(self, s): 
     txt.insert(END, s)
 sys.stdout = PrintToTXT() 
print ('Pandas date range of 8 values in 1 timestamp column adjacent to a numpy random float array of 8 rows and 4 columns, displayed in a Tkinter table') 
print (dframe)
mainloop()

Next steps

Now that you know how to use Tkinter’s Pack() layout manager, let’s move on to other things you can do with Tkinter:

Get a version of Python that’s pre-compiled for Data Science

While the open source distribution of Python may be satisfactory for an individual, it doesn’t always meet the support, security, or platform requirements of large organizations.

This is why organizations choose ActivePython for their data science, big data processing and statistical analysis needs.

Pre-bundled with the most important packages Data Scientists need, ActivePython is pre-compiled so you and your team don’t have to waste time configuring the open source distribution. You can focus on what’s important–spending more time building algorithms and predictive models against your big data sources, and less time on system configuration.

Some Popular Python Packages for Data Science/Big Data/Machine LearningYou Get Pre-compiled – with ActivePython

  • pandas (data analysis)
  • NumPy (multi-dimensional arrays)
  • SciPy (algorithms to use with numpy)
  • HDF5 (store & manipulate data)
  • Matplotlib (data visualization)
  • Jupyter (research collaboration)
  • PyTables (managing HDF5 datasets)
  • HDFS (C/C++ wrapper for Hadoop)
  • pymongo (MongoDB driver)
  • SQLAlchemy (Python SQL Toolkit)

Recent Posts

Scroll to Top