Reputation: 2378
I want to create an excel like interface in python using tkinter which i have created as shown below.
from tkinter import *
window=Tk()
x = [1,2,3,4]
height = 1
width = 4
for i in range(height): # Rows
for j in range(width): # Columns
b = Entry(window, text="")
b.grid(row=i, column=j)
window.mainloop()
How could i return the list x to the tkinter interface? preferably 1 number per cell. Is that possible?
expected result to look something like:
Upvotes: 0
Views: 61
Reputation: 386010
If you are trying to emulate a spreadsheet, you need a way to address the widgets in every row. Once you have that, inserting, deleting, and fetching the data becomes very simple.
The simplest way to do that is to store references to the entry widgets as a list of lists, so that you can reference any cell by its row and column number.
cells = []
for i in range(height): # Rows
row = []
cells.append(row)
for j in range(width): # Columns
b = Entry(window, text="")
b.grid(row=i, column=j)
row.append(b)
You can now use cells
to reference any widget. For example, the widget for row 0, column 2 would be cells[0][2]
.
With this basic structure, you can now easily write functions to get or set whole rows or whole regions at a time.
For example, here's a way to create a set_row
function:
def set_row(rownum, data):
row = cells[rownum]
for entry, value in zip(row, data):
entry.delete(0, "end")
entry.insert(0, value)
For example, to set the first (0) row with the contents of x
you could do:
set_row(0, x)
Getting data from the spreadsheet is also simple:
def get_data():
rows = []
for rownum in range(height):
row = []
rows.append(row)
for columnnum in range(width):
entry = cells[rownum][columnnum]
row.append(entry.get())
return rows
Upvotes: 1
Reputation: 8270
You can define entry
value using insert
:
from tkinter import *
window = Tk()
x = [1, 2, 3, 4]
height = 1
for i in range(height):
for j, val in enumerate(x):
b = Entry(window)
b.insert(0, val)
b.grid(row=i, column=j)
window.mainloop()
Result:
Upvotes: 1