Python GUI猜字游戏
我正在尝试使用tkinter构建一个GUI猜字游戏。我收到一个UnboundLocalError:赋值前引用的局部变量'Guesss',用于'if guess.get()in guesses:'行 我的代码顶部有以下内容:Python GUI猜字游戏,python,user-interface,tkinter,Python,User Interface,Tkinter,我正在尝试使用tkinter构建一个GUI猜字游戏。我收到一个UnboundLocalError:赋值前引用的局部变量'Guesss',用于'if guess.get()in guesses:'行 我的代码顶部有以下内容: global guesses guesses = [] 这就是抛出错误的函数: def play(): while remaining.get() > 0: if guess.get().isalpha() == False or len(gu
global guesses
guesses = []
这就是抛出错误的函数:
def play():
while remaining.get() > 0:
if guess.get().isalpha() == False or len(guess.get()) != 1:
output.set('Invalid input. Please enter a letter from a-z.')
else:
if guess.get() in guesses:
output.set('That letter has already been guessed!')
else:
if guess.get() not in secret_word:
output.set('That letter does not occur in the secret word.')
else:
output.set('That is a good guess! ' + str(guess.get()) + ' occurs ' + \
str(countOccurences(str(secret_word), guess.get())) + ' time(s) in the secret word')
guesses += guess.get()
remaining.set(remaining.get() - 1)
if '_' not in getHint(secret_word, guesses):
result.set('Congratulations! You guessed the secret word: ' + str(secret_word))
break
if remaining == 0:
result = 'Sorry, the secret word was: ' + str(secret_word)
我已经改变了猜测的范围,我已经多次重新定义了它,但没有任何效果。我不知道还有什么可以防止这个错误
任何帮助都将不胜感激。谢谢 在需要使用全局变量的方法中使用
global
关键字
也就是说,将全局猜测放在play()
方法的内部,而不是外部
guesses = []
...
def play():
global guesses
while remaining.get() > 0:
if guess.get().isalpha() == False or len(guess.get()) != 1:
....
不过,使用它不要太舒服。当您对Python有了更多的经验后,在某些时候您可能会希望使用类来存储和访问需要在方法之间共享的变量
最后,对于将来的问题,请考虑使用一个标题来确定实际问题,而不是你的更广泛的意图。这样你就更有可能得到有用的答案