Python - Tkinter:错误说我的索引超出范围,当有

时间:2014-12-26 13:40:27

标签: python list python-3.x error-handling tkinter

所以,我正在为一个学校项目制作这个刽子手游戏,并且遇到了一个问题,我不能为我的生活弄清楚甚至为什么它会发生。

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超出了范围。我的问题是,为什么会发生这种情况,我该怎么做才能解决。

节日快乐!

1 个答案:

答案 0 :(得分:3)

以下行创建一个包含单个元素的列表(elemnt是一个字长已长的字符串“_ _ _ ...”字符串):

hidden_word = ["_ " * len(word)]

访问元素(索引> 0)会导致IndexError,因为列表中只有一个元素。

您可能想要创建多个元素的列表:

hidden_word = ["_ "] * len(word)

>>> ["_ " * 3]
['_ _ _ ']
>>> ["_ "] * 3
['_ ', '_ ', '_ ']