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
我试了很多次,当我按下按钮时,错误出现了,有时无法识别正确的单词。然而,有时当我按下一次按钮,整个刽子手就出来了。有人知道如何解决上述问题吗?现在,对于这个问题,我已经通过理解答案来解决它,并尝试自己编写一次,最后程序成功运行
您的问题是希望函数是lambda,而字符是静态的。今天对你们来说是个好日子,因为我也在努力制作屏幕键盘。请注意命令中恰当命名的函数
相关问题 更多 >
编程相关推荐