0

I'm creating a hangman game in python to learn the language. Inside of root, I have a menu frame, which includes a "new game" option. If the user clicks 'new game' in the middle of a game, I want to destroy the current game frames, leave the menu frame, and then rebuild the game frames with a new game, but I keep getting an 'index out of range' error.

I can see that the children are there when I print root.children.values(). The first time the game runs, only one frame exists (the menu). The second time the game runs, the game frames exist, and those are also shown as children inside root.winfo_children(). Trying to iterate through the children and destroying them works until the last, which gives me an out of range error, but I can't figure out why since I can see the number of children and see that it matches the values.

print(root.children.values())
childcounter = 0
for children in root.winfo_children():
    if childcounter > 0: #skip menu child frame
        print(childcounter)
        root.winfo_children()[childcounter].destroy()
    childcounter += 1


random.shuffle(wordlist)
randomword = wordlist[0]
wordframe = ttk.Frame(master=root)
wordframe.config(height=100, width=398)
letterstoguess = list(randomword)
for letter in letterstoguess:
    addletterbutton = Button(wordframe, text="_", height=3, padx=2)
    addletterbutton.pack(side=LEFT, fill=X, expand=1)
wordframe.pack_propagate(False)
wordframe.pack(side=TOP, fill=BOTH, expand=YES)
lettersframe = ttk.Frame(master=root)
lettersframe.config(width=398)
lettersframe.pack_propagate(False)
lettersframe.pack(side=BOTTOM, pady = 5)
hangmanframe = ttk.Frame(master=root)
hangmanframe.config(height=200, width=398)
hangmanframe.pack_propagate(False)
hangmanframe.pack(side=TOP)
ph=PhotoImage(file=imagelist[0])
photolabel = Label(hangmanframe, image=ph)
photolabel.image=ph
photolabel.pack()

rowvar = 0
colvar = 0
for letter in letters:
    addletterbutton = Button(lettersframe, text=letter, width=2, padx=2, command=partial(guess,letter))
    addletterbutton.grid(row=rowvar,column=colvar,ipadx=1,padx=1)
    colvar += 1
    if colvar == 13:
        colvar = 0
        rowvar+=1

The debugger shows:

dict_values([tkinter.ttk.Frame object .!frame])

the first time it runs, and then:

dict_values([tkinter.ttk.Frame object .!frame, tkinter.ttk.Frame object 
.!frame2, tkinter.ttk.Frame object .!frame3, tkinter.ttk.Frame object 
.!frame4])

the second time I click 'new game'. The childcounter iterator shows:

1
2
3

as expected, but then this error occurs:

line 21, in newgame
    root.winfo_children()[childcounter].destroy()
IndexError: list index out of range
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Edward Glasser
  • 183
  • 4
  • 17

0 Answers0