[Tutor] Tkinter grid question

Peter Otten __peter__ at web.de
Fri Apr 7 04:01:21 EDT 2017


Phil wrote:

> Thank you for reading this.
> 
> This is my first attempt at using Tkinter and I've quickly run into a
> problem.
> 
> If e is a one dimensional list then all is OK and I can delete and insert
> entries. The problem comes about when the list is made two dimensional, as
> follows:
> 
> from tkinter import *
> 
> master = Tk()
> 
> e = [None] * 6 , [None] * 2

In the above line you are creating a 2-tuple consisting of two lists:

>>> [None]*6, [None]*2
([None, None, None, None, None, None], [None, None])

What you want is a list of lists
[
[None, None],
[None, None],
...
]

You can create such a list with

>>> [[None] * 2 for _ in range(6)]
[[None, None], [None, None], [None, None], [None, None], [None, None], 
[None, None]]

> 
> for i in range(6):
>     for j in range(2):
>         e[i][j] = Entry(master, width=5)
>         e[i][j].grid(row=i, column=j)
>         e[i][j].insert(0,"6")
> 
> mainloop( )
> 
> Traceback (most recent call last):
>   File "/home/pi/tkinter_example.py", line 50, in <module>
>     e[i][j] = Entry(master, width=5)
> IndexError: tuple index out of range
> 
> I can see that the problem occurs when i is greater than 1 which makes me
> think that my method of attempting to create a two denominational array of
> edit boxes is wrong.
> 
> I've search for an example but haven't turned up anything. Where had I
> failed?
 
As shown above this has nothing to do with tkinter. Personally I would 
create the list of list dynamically

entries = []
for row in range(6):
    entries_row = []
    entries.append(entries_row)
    for column in range(2):
        entry = Entry(master, width=5)
        entry.grid(row=row, column=column)
        entry.insert(0,"6")
        entries_row.append(entry)

or even use a dict with (row, column) keys:

def make_entry(row, column):
    entry = Entry(master, width=5)
    entry.grid(row=row, column=column)
    entry.insert(0,"6")
    return entry

master = Tk()

entries = {
    (r, c): make_entry(r, c)
    for r in range(6) for c in range(2)
}





More information about the Tutor mailing list