Create table in Python using Tkinter

Here we are going to discuss creating a table in Python using Tkinter. Before moving in further let’s first understand what is Tkinter. Tkinter is a standard yet powerful GUI library in Python. GUI means ‘ Graphic User Interface’ which provides a link between the user and the code running in the background. So how does it help? Tkinter provides a strong object-oriented interface that helps to create a user interface.

How to create a table in Python with Tkinter

from tkinter import Tk, Entry, Button, Label, Text, END
class Window(object):

    def __init__(self, master):
        self.master = master

        self.label_cols = Label(self.master, text='Number of Columns')
        self.label_rows = Label(self.master, text='Number of Rows')
        self.entry_cols = Entry(self.master)
        self.entry_rows = Entry(self.master)

        self.btn = Button(self.master, text='Generate', command=self.create_table)
        self.out = Text(self.master)

        self.label_cols.grid(row=0, column=0, sticky='E')
        self.entry_cols.grid(row=0, column=1, sticky='W')

        self.label_rows.grid(row=1, column=0, sticky='E')
        self.entry_rows.grid(row=1, column=1, sticky='W')

        self.btn.grid(row=2, column=0, columnspan=2)
        self.out.grid(row=3, column=0, columnspan=2)

    def create_table(self):

        table = ''

        cols = self.entry_cols.get()
        rows = self.entry_rows.get()

        if (rows.isdigit() and int(rows) > 0) and (cols.isdigit() and int(cols) > 0):

            for r in range(int(rows) + 2):

                if r is not 0:
                    table = table + '\n'

                for c in range(int(cols) + 1):

                    if r is 1 and c is not int(cols):
                        table = table + '|---'
                        table = table + '|   '

        self.out.delete(1.0, END)
        self.out.insert(END, table)

root = Tk()
m = Window(root)

Let us understand the working of the code:

The first step is always to import the desired libraries or modules from a library.

Next, we create a Class which I named as Window.

  1.  Window class has a constructor and a method named as create_table.
  2. Constructor: The main function of this constructor is to accept values from the user. This data will be used to create the table accordingly.
  3. create_table: This method of the class Window actually creates the table based on the values received from the constructor. We start a loop that continues until the input is met.

Finally, we create an object of the Tkinter named as root. We then use this object to provide the data to the class Window whose object is created as m.

Create a table in Tkinter in Python

Also read: Create a simple GUI calculator using Tkinter in Python

Leave a Reply