首先,我知道那里有类似的解决方案,并且我已经查看了所有这些解决方案。他们都没有工作 - 这不是重复的。我的程序是一个刽子手程序,它根据玩家给出的错误猜测来更新图像。这是我的代码。随意编辑和删除不相关的代码。我没有,因为我不明白这个错误。编码:
import random,time,sys
from tkinter import *
sys.path.append('C:/Users/Thornton/Desktop/Python Stuff/PyHang/images/') #defining the full path
class App:
def __init__(self,master):
frame=Frame(master)
frame.pack()
global e1,game
Label(frame,text='Guess').grid(row=2)
e1=Entry(frame)
e1.grid(row=2,column=1)
slider=Scrollbar(frame)
slider.grid(row=1,column=2)
self.game=Listbox(frame,height=3,yscrollcommand=slider.set)
self.game.grid(row=1,column=1)
slider.config(command=self.game.yview)
self.status=Canvas(frame,width=220,height=125) #creating the canvas
self.status.grid(row=0,column=1)
Button(frame,text='OK',command=self.guess).grid(row=2,column=2)
root.bind('<Return>',self.guess)
Button(frame,text="New\nGame",command=self.new_game).grid(row=1,column=0)
root.bind('<Home>',self.new_game)
self.new_game()
def guess(self,event=None):
frame=Frame()
frame.pack()
global losses
letter=e1.get().strip()
if len(letter)!=1 or letter.isdigit() or letter in self.used:
pass
else:
self.used.append(letter)
if letter in self.secret:
self.game.insert(END,"\n",'Correct!')
positions=[i for i,item in enumerate(self.secret) if item==letter]
for place in positions:
self.display[place]=letter
else:
self.game.insert(END,"\n",'Incorrect.')
self.losses+=1
self.status.image=PhotoImage(str(losses) + '.gif') #updating image
self.game.insert(END,''.join(self.display),'Used: ' + ''.join(self.used))
if self.losses==6:
self.game.insert(END,'You Lose.',"(" + ''.join(self.secret) + ")")
elif self.display==self.secret:
self.game.insert(END,'You Win!')
self.game.yview(END)
e1.delete(0,END)
def new_game(self,event=None):
frame=Frame()
frame.pack()
global game,losses,used,secret,display
self.secret=list(random.choice(open('dictionary.txt').readlines()))
del self.secret[-1]
self.losses=0
self.used=[]
self.display=['*' for letter in self.secret]
self.status.image=PhotoImage(file='0.gif') #resetting image
self.status.create_image(image=self.status.image)
e1.delete(0,END)
self.game.delete(0,END)
self.game.insert(END,''.join(self.display))
root = Tk()
root.title('PyHang 2.0')
app = App(root)
root.mainloop()
输出:
File "C:\Users\Thornton\Desktop\Python Stuff\PyHang\pyhang2.0.py", line 72, in new_game
self.status.image=PhotoImage(file='0.gif')
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: couldn't open "0.gif": no such file or directory
图像在文件夹images
中,范围从0
到6.gif
并对应于变量losses
。所有文件都存在,如您所见,我已经定义了完整路径。请耐心等待,因为我是 tkinter 的新手。