0

I am writing a GUI using tkinter, and I have several lines consisting of a Entry widget inline with a Button widget. When I press the button, the callback opens the askdirectory dialog, and the directory choosen is written in the Entry widget, from the same line as the button clicked.

To get to a more elegant solution than just copy/paste 12 times the code, I wrote the following:

    for i in range (0,12):
        e[i] = Entry(master)
        e[i].insert(0, "<Choose a directory...>")
        e[i].config(width=70)
        e[i].grid(row=i+2, column=0, sticky=NW, columnspan=2)
        b[i] = Button(master, text="Choose directory", command=lambda: self.getDir(e[i]))
        b[i].grid(row=i+2, column=2, sticky=N)

And the callback function:

def getDir(self, e):
    '''Retrieve directory and write it on the right "Entry" widget'''
    dirName = askdirectory(title='Choose a directory:')
    e.delete(0, END)
    e.insert(0, dirName)

When I run the script, I get the "list index out of range" error.

From my understanding, it is because i - which is used later on the code -, is not the index anymore, only in the moment I am building the buttons, right?

So, what should I do to make the callback understand which Button was clicked and to which Entry it should write?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

0

I can only guess since you didn't post the error message: could simply be the lenght of e and b! e and b need to be lists or tuples with at least the lenght of 12...or if you just want to process your code 12 times you dont need the [i] at all. I would have posted this as a comment but I don't have enough points to do so :(

Heiner Früh
  • 127
  • 5