How do I update a specific row and column in tkinter table?

Viewed 34

I am creating a table like this in tkinter, https://www.geeksforgeeks.org/create-table-using-tkinter/. I am unable to update specific sections, have not been able to find anything that works yet.


# code for creating table
for i in range(5):
    for j in range(5):
        
        example_table = tkinter.Entry(root, width=20, fg='blue',
                    font=('Arial',16,'bold'))
    
        example_table.grid(row=i, column=j)
        example_table.insert(tkinter.END, "f")

After creating the table, If I want to update the 4th row and 4th column, how would I do so?

1 Answers

The simplest way would be to keep a reference to each entry within the table class using a 2d list, and then you can just access each entry from it's index value

for example:

from tkinter import *

class Table:
    def __init__(self,root):
        self.entries = []  # now each of the entries will be stored in rows
        # code for creating table
        for i in range(total_rows):
            row = []  # this will actually contain 1 row of cell entry widgets
            for j in range(total_columns):
                e = Entry(root, width=20, fg='blue',
                               font=('Arial',16,'bold'))
                e.grid(row=i, column=j)
                e.insert(END, lst[i][j])
                row.append(e)
            self.entries.append(row)

lst = [(1,'Raj','Mumbai',19),
       (2,'Aaryan','Pune',18),
       (3,'Vaishnavi','Mumbai',20),
       (4,'Rachna','Mumbai',21),
       (5,'Shubham','Delhi',21)]

# this is the function that updates the table
def updateTable(row, col):
    e = t.entries[row][col]  # get the entry at row, col
    val = e.get()            #  Get the current text in cell
    e.delete(0,last=len(val))  # remove current text
    e.insert(END, "Something Differnet")   # insert new text

root = Tk()
t = Table(root)

# clicking this button will change the cell text for 4th column 4th row
B = Button(root, text="Change Table", command=lambda: updateTable(3, 3))
B.grid(row=5,column=1, columnspan=2)

root.mainloop()


Related