【问题标题】:Python - Tkinter: error saying my index is out of range, when there isPython - Tkinter:错误说我的索引超出范围,当有
【发布时间】: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


    【解决方案1】:

    下面这行创建了一个包含单个元素的列表(元素是一个字长为“_ _ _ ...”的字符串):

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

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

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

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

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

    【讨论】:

    • 所以我需要做的是更改方括号?耶稣我是哑巴哈哈,谢谢!我有一个额外的问题:现在我有这个工作,当我点击按钮时的输出是正确的,但如果有多个字母实例,它不会替换那个,因此如果一个字母重复我永远无法完成一个字!我不知道从哪里开始:/
    • @18166, list.index 返回第一次出现的索引。不要使用它,而是遍历列表项,检查项是否与输入字符匹配,并对匹配执行适当的操作。
    猜你喜欢
    • 1970-01-01
    • 2016-04-17
    • 2015-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多