[Tutor] Recursive Tkinter buttons

Michael Lange klappnase at freenet.de
Fri Feb 25 12:21:18 CET 2005


On Fri, 25 Feb 2005 20:19:15 +1300
Liam Clarke <cyresse at gmail.com> wrote:

> >                
> >                 for i in range(0,10):
> >                         print i
> >                         buttonlabel = "field " +str(i)
> >                         button[i].append = Button (text=buttonlabel)
> >                         button[i].grid(column=3, row = i+3)
> > 
> > The current error is:
> > 
> >   File "report.py", line 80, in createWidgets
> >     button[i].append = Button (text=buttonlabel)
> > IndexError: list index out of range
> > 
>  button = []
> for i in range(0,10):
>      print i
>      print button[i]
> 
> 
> Will cause the exact same error as button[i].append. Why? button=[],
> it has no index.
> Perhaps you just mean button[i] = Button (text=buttonlabel)?
> 
> Regards,
> 
> 
Or :

buttonlist = []
for i in range(0, 10):
    print i
    buttonlabel = "field" + str(i)
    b = Button(text=buttonlabel)
    b.grid(column=3, row=i+3)
    buttonlist.append(b)

Remember what you are doing when you call "button[i].append = Button(text=buttonlabel)":
button is a list of Tkinter.Button objects, so button[i] is the "i-th" item in this list
and that's exactly one more than the list actually contains, so you get an IndexError .
However, if this IndexError wouldn't occur, it didn't help much, because you would
probably get an AttributeError, saying something like "Tkinter.Button instance has no attribute 'append'".
Even without this AttributeError nothing would be won, because the list's append() method returns None,
so you would have:  None = Button(text=buttonlabel) which is probably not what you intended.

You see, in my example above I called the list "buttonlist" instead of "button"; maybe this naming
helps avoid confusion .

Best regards

Michael


More information about the Tutor mailing list