Python provides several options for developing graphical user interfaces (GUIs), with Tkinter being the most popular choice. Tkinter serves as the standard Python interface to the Tk GUI toolkit, which comes included with Python installations. It’s the quickest and easiest way to build GUI applications. Creating a GUI with Tkinter is straightforward and user-friendly.
Creating Tables Using Tkinter
Tables are useful for organizing data into rows and columns. While Tkinter does not include a dedicated Table widget, we can create tables using alternative methods. For instance, we can arrange Entry widgets in a grid format to simulate a table.
To create a table with five rows and four columns, we can utilize nested for loops as follows:
for i in range(5):
for j in range(4):
Inside these loops, we have to create an Entry widget by creating an object of Entry class, as:
e = Entry(root, width=20, fg='blue', font=('Arial', 16, 'bold')
Next, we need to implement the logic for positioning the Entry widgets in rows and columns. This can be achieved using the grid() method, where we specify the row and column indices for each widget, as follows:
# here i and j indicate
# row and column positions
e.grid(row=i, column=j)
We can insert data into the Entry widget using insert() method, as:
e.insert(END, data)
In this context, ‘END’ signifies that new data will be appended to the end of the existing content in the Entry widget. The following program demonstrates this logic by using data from a list.
We have created a list containing five tuples, where each tuple includes four values representing a student’s ID, name, city, and age. As a result, we will have a table with five rows and four columns. This approach can also be adapted to display data retrieved from a database in a tabular format.
Let’s us check out the full code:
# Python program to create a table
from tkinter import *
class Table:
def __init__(self,root):
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
self.e = Entry(root, width=20, fg='blue',
font=('Arial',16,'bold'))
self.e.grid(row=i, column=j)
self.e.insert(END, lst[i][j])
# take the data
lst = [(1,'Rajesh','Delhi',19),
(2,'Paul','United kingdom',18),
(3,'Sonia','Mumbai',20),
(4,'Rachna','Hyderabad',21),
(5,'Dunccan','New york',21)]
# find total number of rows and
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
t = Table(root)
root.mainloop()
Output:
Let us check out how we can innovate the above table
from tkinter import *
class Table:
def __init__(self, root):
# Create headers
headers = ['ID', 'Name', 'City', 'Age']
for j in range(total_columns):
header = Label(root, text=headers[j], bg='lightblue', font=('Arial', 14, 'bold'))
header.grid(row=0, column=j, padx=5, pady=5)
# Create table with interactive cells
for i in range(1, total_rows + 1):
for j in range(total_columns):
self.e = Entry(root, width=20, fg='black', font=('Arial', 14), bd=2, relief='groove')
self.e.grid(row=i, column=j, padx=5, pady=5)
self.e.insert(END, lst[i-1][j])
self.e.bind("<Button-1>", self.on_click) # Bind click event
def on_click(self, event):
"""Change the background color of the clicked cell."""
current_widget = event.widget
current_color = current_widget.cget("bg")
new_color = "lightyellow" if current_color == "white" else "white"
current_widget.config(bg=new_color)
# Data for the table
lst = [
(1, 'Rajesh', 'Delhi', 19),
(2, 'Paul', 'United Kingdom', 18),
(3, 'Sonia', 'Mumbai', 20),
(4, 'Rachna', 'Hyderabad', 21),
(5, 'Dunccan', 'New York', 21)
]
# Determine the number of rows and columns
total_rows = len(lst)
total_columns = len(lst[0])
# Create the main window
root = Tk()
root.title("Interactive Table")
root.geometry("600x300") # Set a larger window size
# Create the table
table = Table(root)
# Start the main event loop
root.mainloop()
Enhancements Made:
- Header Labels: Added a header row to identify the columns.
- Cell Interaction: Cells change color when clicked, making them more interactive.
- Improved Styling: Adjusted font size, colors, and borders for a cleaner look.
- Dynamic Resizing: You can set a larger window size to accommodate the table.
Feel free to modify further to suit your design preferences!
Output:

Explanation of the above code:
Import Statement
from tkinter import *: Imports all classes and functions from the Tkinter library, which is used for creating GUI applications.
Table Class Definition
class Table:: Defines a class namedTablethat will create a GUI table.
Initialization Method
def __init__(self, root):: Constructor method for initializing the table.headers = ['ID', 'Name', 'City', 'Age']: Defines the column headers for the table.- Loop for Headers:
for j in range(total_columns):: Iterates over the number of columns.header = Label(...): Creates a label for each header with specified properties (text, background color, font).header.grid(...): Places the header label in the grid layout at row 0.
Creating Interactive Cells
- Loop for Table Cells:
for i in range(1, total_rows + 1):: Iterates over the number of rows, starting from 1 (to leave the first row for headers).- Inner Loop:
for j in range(total_columns):: Iterates over each column.self.e = Entry(...): Creates an Entry widget (editable cell) with specified properties.self.e.grid(...): Places the Entry widget in the grid layout.self.e.insert(END, lst[i-1][j]): Inserts data from the listlstinto the corresponding cell.self.e.bind("<Button-1>", self.on_click): Binds a click event to each cell, calling theon_clickmethod when clicked.
Cell Click Handling
def on_click(self, event):: Method to handle click events on table cells.current_widget = event.widget: Gets the widget that was clicked.current_color = current_widget.cget("bg"): Retrieves the current background color of the cell.new_color = "lightyellow" if current_color == "white" else "white": Determines the new color based on the current color.current_widget.config(bg=new_color): Updates the cell’s background color.
Data Definition
lst = [...]: Creates a list of tuples containing sample data (student ID, name, city, age).
Row and Column Calculation
total_rows = len(lst): Calculates the number of rows based on the data list.total_columns = len(lst[0]): Calculates the number of columns based on the first tuple in the list.
Main Window Setup
root = Tk(): Creates the main application window.root.title("Interactive Table"): Sets the title of the window.root.geometry("600x300"): Defines the size of the window.
Table Creation
table = Table(root): Instantiates theTableclass, creating the table in the main window.
Main Event Loop
root.mainloop(): Starts the Tkinter event loop, allowing the application to run and respond to user actions.
This code creates a basic interactive table with headers and editable cells, enhancing user interaction through visual feedback on clicks.
Conclusion
Creating tables in Python using Tkinter is both straightforward and efficient, making it an excellent choice for developers looking to build user-friendly GUI applications. With the ability to display data in a structured format, customize cell interactions, and enhance visual appeal, Tkinter provides the necessary tools to craft interactive tables with ease. Whether you’re working with simple datasets or integrating data from more complex sources like databases, Tkinter allows you to present information clearly and effectively.
As you continue to explore its features, you’ll find that building intuitive interfaces becomes an enjoyable and rewarding experience. Start creating your own tables today and elevate your Python applications!





Leave a Reply