【发布时间】:2015-02-23 19:31:47
【问题描述】:
所以,我正在为一个学校项目制作这款刽子手游戏,但遇到了一个问题,我终其一生都无法弄清楚为什么会发生这种情况。
word_list = ["APPLE", "PEAR", "BANNANA"]
word = word_list [random.randint(0,2)]
hidden_word = ["_ " * len(word)]
print (word)
这段代码是一个列表,然后将其中一个单词做成一个字符串变量:
word = word_list [random.randint(0,2)]
然后我通过获取长度创建一个新列表,该列表是隐藏单词,'_'用于隐藏:
hidden_word = ["_ " * len(word)]
然后我打印这个词(用于开发)
print (word)
关于有问题的代码。
def click_1 (key):
if str(key) in word:
key_1 = word.index(key)
print (key_1)
hidden_word[key_1] = key
print (hidden_word)
else:
print ("Nope")
return letter
r = c = 0
for letter in string.ascii_uppercase:
Button(letter_frame, text=letter, command=functools.partial(click_1, letter)).grid(row=r, column=c, sticky=W)
c += 1
if c > 12:
c = 0
r += 1
这会使按钮出现,当我单击带有字母的按钮时,它会检查它是否在单词中,然后(目前)打印:
BANNANA
>>> 0
['B']
如果这个词是bannana。问题是当我按下 A 时:
1
出现了,如果我按别的东西,就会出现这个错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/idlelib/run.py", line 121, in main
seq, request = rpc.request_queue.get(block=True, timeout=0.05)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/queue.py", line 175, in get
raise Empty
queue.Empty
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 1475, in __call__
return self.func(*args)
File "/Users/alexeacott/Desktop/Hangman.py", line 24, in click_1
hidden_word[key_1] = key
IndexError: list assignment index out of range
最后一行是最有趣的,因为显然 N 超出了范围。我的问题是,为什么会发生这种情况,我可以做些什么来解决。
节日快乐!
【问题讨论】:
标签: python list python-3.x error-handling tkinter