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()`
Top comments (0)