Python Tkinter – How to display a table editor in a text widget?

TkinterPythonGUI-Programming

Tkinter is a Python-based GUI toolkit that is used to create fullfledged desktop applications. Tkinter has a variety of modules and class libraries to help developers create userfriendly applications quickly and easily.

The Text widget in tkinter provides users a way to create a text editor that accepts multiline user-input. You can configure and customize its properties and attributes. Suppose you want to represent your 2-dimensional data in a table using only the Text widget. To create a table in a Text widget, we have to first create a 2-d array consisting of data that needs to be displayed in the table.

Steps

You can follow the steps given below −

  • Import the required libraries.

  • Create a 2-d array containing data in rows and columns.

  • Iterate over each row and column and create a Text widget.

  • Use the grid(row, col) geometry manager to represent the data in a grid of rows and columns.

  • Now, insert the array data into the Text widget.

  • Run the code to display the output.

Example

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame
win = Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create a text widget
array = [("1","2","3","4","5", "6", "7"),("Sun","Mon","Tue","Wed","Thu", "Fri", "Sat"),("aaa","acc","add","aee","abb", "abd", "acd"),("A","B","C","D","E","F","G")]

for x in range(4):
   for y in range(7):
      text = Text(win, width=10, height=5)
      text.grid(row=x,column=y)
      text.insert(END, array[x][y])

win.mainloop()

Output

Running the above code will display a tablelike Text widget separated by some rows and columns. You can configure and edit these rows and columns.

raja
Published on 22-Dec-2021 11:12:08

Advertisements