首页 > 解决方案 > 为什么在以下代码中会出现此错误?IndexError:列表分配索引超出范围

问题描述

from tkinter import *
alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def callback(x):
    label.configure(text='Button {} clicked'.format(alphabet[x]))

root= Tk()

label = Label()
label.grid(row=1,column=0, columnspan=26)

buttons= []*26  #create a list to hold 26 buttons
for i in range(26):
buttons[i] = Button(text=alphabet[i], command = lambda x=i: callback(x))

buttons[i].grid(row=0,column=i)

mainloop()

运行此代码时,会产生以下错误: Traceback (most recent call last): File "./alphabet_click.py", line 16, in buttons[i] = Button(text=alphabet[i], command = lambda x =i: callback(x)) IndexError: 列表赋值索引超出范围

我需要做什么来解决这个错误?

标签: python-3.x

解决方案


正如@jonsharpe 所说,buttons等于[]after buttons= []*26。所以只需删除*26和替换或buttons[i] = Button(...)使用buttons.append(Button(...))地图:

buttons = list(map(lambda letter: Button(text=letter,
                                         command=callback), alphabet))

推荐阅读