I am creating a basic hangman game using tkinter. The last thing that I need to do is to add a widget that has an image to show the actual hangman. However, I keep getting this error whenever I try anything:
File "C:\Program Files (x86)\Python\lib\tkinter\__init__.py", line 3287, in __init__
Image.__init__(self, 'photo', name, cnf, master, **kw)
File "C:\Program Files (x86)\Python\lib\tkinter\__init__.py", line 3243, in __init__
self.tk.call(('image', 'create', imgtype, name,) + options)
_tkinter.TclError
I am presuming that I should use PhotoImage, as all the images are in .gif format. I have commented in the code below what needs to go where as far as I think. As it is below, it runs fine. This one uses a massive dictionary file so for the sake of debugging I suggest that you guys make a small list of words.
import random,time
from tkinter import *
def guess():
global losses
letter=e1.get().strip()
if len(letter)!=1 or type(letter)!=str or letter in used:
game.insert(END,'INVALID INPUT')
else:
used.append(letter)
if letter in secret:
game.insert(END,"\n",'Correct!')
positions=[i for i,item in enumerate(secret) if item==letter]
for place in positions:
display[place]=letter
else:
game.insert(END,"\n",'Incorrect.')
losses+=1
#change image here -images go from 0 to 6.gif and correspond with the variable losses
game.insert(END,''.join(display),'Used: ' + ''.join(used))
if losses==6:
game.insert(END,'You Lose.')
elif display==secret:
game.insert(END,'You Win!')
game.yview(END)
def new_game():
global photo,losses,used,secret,display
secret=list(random.choice(open('dictionary.txt').readlines()))
del secret[-1]
#reset image back to first image
losses=0
used=[]
display=['*' for letter in secret]
game.delete(0,END)
game.insert(END,''.join(display))
master=Tk()
master.title('PyHang 2.0')
Label(master,text='Guess').grid(row=2)
e1=Entry(master)
e1.grid(row=2,column=1)
slider=Scrollbar(master)
slider.grid(row=1,column=2)
game=Listbox(master,yscrollcommand=slider.set)
game.config(height=3)
game.grid(row=1,column=1)
slider.config(command=game.yview)
#create original widget, first image is "\images\0.gif" in an external folder
Button(master,text='OK',command=guess).grid(row=2,column=2)
Button(master,text="New\nGame",command=new_game).grid(row=1,column=0)
new_game()
mainloop()
I know that the code in the guess function is hideous, and this program should probably be in class format but that's for another day. FYI, this is my first tkinter program so if the answer's really obvious, please be patient. Any assistance would be greatly appreciated.