【发布时间】:2020-07-29 17:07:26
【问题描述】:
def game():
global no_of_guesses
no_of_guesses = 0
imgLb.configure(image=photos[0])
target_word = random.choice(list_of_words)
lblword.set(' '.join('_'*len(target_word)))
def guess(letter):
global no_of_guesses
if no_of_guesses < 11:
guessed = list(lblword.get())
for c in range(len(guessed)):
if guessed[c] == letter:
lblword.set(''.join(guessed))
messagebox.showinfo('Hangman','You guess correctly')
else:
no_of_guesses += 1
imgLb.configure(image=photos[no_of_guesses])
if no_of_guesses == 11:
messagebox.showwarning('Hangman','Game Over!')
imgLb = Label(win)
imgLb.grid(row=0,column=0,columnspan=3,padx=10,pady=40)
imgLb.configure(image=photos[0])
lblword = StringVar()
WordLb = Label(win,textvariable=lblword)
WordLb.grid(row=0,column=3,columnspan=6,padx=10)
n = 0
for char in ascii_uppercase:
Button(win,text=char,command=lambda char=char:guess(char),width=4).grid(row=1+n//9,column=n%9)
n += 1
错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "E:/Python/Python Projects Fun/hangman/hangman_code.py", line 52, in <lambda>
Button(win,text=char,command=lambda char=char:guess(char),width=4).grid(row=1+n//9,column=n%9)
File "E:/Python/Python Projects Fun/hangman/hangman_code.py", line 37, in guess
imgLb.configure(image=photos[no_of_guesses])
IndexError: list index out of range
我尝试了很多次,当我按下按钮时,一旦出现错误,有时无法识别正确的单词。但是有时当我按下按钮一次时,整个刽子手就出来了。有人知道如何解决上述问题吗?现在对于这个问题,我已经通过理解答案来解决它并尝试自己编写一次,最后程序成功运行。
【问题讨论】:
-
对于
IndexError,我猜你会想要photos[no_of_guesses - 1]而不是photos[no_of_guesses]if len(photos)==11 -
我更改了照片[no_of_guesses-1],当我按下不匹配的字母时,它显示警告游戏结束,而不是进行 10 次猜测
-
那我建议你创建一个Minimal, Reproducible Example
-
相反,我在 def game() 中更改了全局 no_of_guesses,但仍然出现错误消息:UnboundLocalError: local variable 'no_of_guesses' referenced before assignment
标签: python user-interface tkinter