On this link is this code example that generates a entry grid:
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=10, 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,'Raj','Mumbai',19),
(2,'Aaryan','Pune',18),
(3,'Vaishnavi','Mumbai',20),
(4,'Rachna','Mumbai',21),
(5,'Shubham','Delhi',21)]
# find total number of rows and
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
root.geometry("800x600")
t = Table(root)
root.mainloop()
This is the output:
I want to update 1st row, 2nd column. How do I do that? I know that once I named an Entry I can use the following code:
self.e.delete(0, END)
self.e.insert(0, "update string")
but since I used grid I do not know how to identify one particular Entry from that grid.
Thanks.
You can create a 2-D list to store the references of those Entry
widgets, then you can use this list to update the entry you want.
Also I would suggest:
lst
to Table.__init__()
instead of accessing it directlyfrom tkinter import *
class Table:
def __init__(self, root, values):
total_rows = len(values)
total_columns = len(values[0])
# create a 2-D list to store the entry widgets
self.entries = [[None]*total_columns for _ in range(total_rows)]
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
e = Entry(root, width=10, fg='blue', font=('Arial',16,'bold'))
e.grid(row=i, column=j)
e.insert(END, values[i][j])
self.entries[i][j] = e # store entry into list
# function to get value of entry at (row, col)
def get(self, row, col):
try:
return self.entries[row][col].get()
except IndexError as ex:
print("Error on Table.get():", ex)
# function to set value of entry at (row, col)
def set(self, row, col, value):
try:
self.entries[row][col].delete(0, "end")
self.entries[row][col].insert("end", value)
except IndexError as ex:
print("Error on Table.set():", ex)
# take the data
lst = [(1,'Raj','Mumbai',19),
(2,'Aaryan','Pune',18),
(3,'Vaishnavi','Mumbai',20),
(4,'Rachna','Mumbai',21),
(5,'Shubham','Delhi',21)]
# create root window
root = Tk()
root.geometry("800x600")
t = Table(root, lst) # pass lst to Table()
# update entry at row 0 column 1
t.set(0, 1, "hello")
root.mainloop()