Python 刽子手可以';当我按下屏幕上的键盘按钮时,它不能正常工作 def game(): 全球无猜测 无猜测=0 imgLb.configure(图像=照片[0]) 目标单词=随机选择(单词列表) lblword.set(“”.join(“”*len(目标词))) def猜测(字母): 全球无猜测 如果没有任何猜测
错误:Python 刽子手可以';当我按下屏幕上的键盘按钮时,它不能正常工作 def game(): 全球无猜测 无猜测=0 imgLb.configure(图像=照片[0]) 目标单词=随机选择(单词列表) lblword.set(“”.join(“”*len(目标词))) def猜测(字母): 全球无猜测 如果没有任何猜测,python,user-interface,tkinter,Python,User Interface,Tkinter,错误: 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_
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
Tkinter回调中出现异常
回溯(最近一次呼叫最后一次):
文件“C:\Python38\lib\tkinter\\ uuuuu init\uuuuuu.py”,第1883行,在调用中__
返回self.func(*args)
文件“E:/Python/Python Projects Fun/hangman/hangman_code.py”,第52行,在
按钮(win,text=char,command=lambda char=char:guess(char),width=4)。网格(行=1+n//9,列=n%9)
文件“E:/Python/Python Projects Fun/hangman/hangman_code.py”,第37行,在guess中
configure(图像=照片[没有猜测])
索引器:列表索引超出范围
我试了很多次,当我按下按钮时,错误出现了,有时无法识别正确的单词。然而,有时当我按下一次按钮,整个刽子手就出来了。有人知道如何解决上述问题吗?现在,对于这个问题,我已经通过理解答案解决了它,并尝试自己编写了一次,最后程序成功运行。您的问题是希望函数为lambda,而字符为静态。今天对你们来说是个好日子,因为我也在努力制作屏幕键盘。请注意命令中恰当命名的函数
按钮(win,text=char,command=partial(guess,char),width=4)。网格(行=1+n//9,列=n%9)
对于索引器
,我猜您想要的是照片[无猜测-1]
而不是照片[无猜测]
如果len(照片)==11I更改照片[无猜测-1]当我按下不匹配的字母时,它显示警告游戏结束,而不是进行10次猜测。然后我建议您在def game()中创建一个已更改且已为全局的no_of_guesses,并且仍然显示错误消息:UnboundLocalError:赋值前引用的局部变量'no_of_of_guesses'
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