python-3.x - 为什么在以下代码中会出现此错误?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: 列表赋值索引超出范围
我需要做什么来解决这个错误?
解决方案
正如@jonsharpe 所说,buttons
等于[]
after
buttons= []*26
。所以只需删除*26
和替换或buttons[i] = Button(...)
使用buttons.append(Button(...))
地图:
buttons = list(map(lambda letter: Button(text=letter,
command=callback), alphabet))
推荐阅读
- javascript - 按属性名称搜索嵌套对象并复制到新对象不会导致所有对象都被复制
- assembly - 当前视频缓冲区段地址是否记录在内存位置?
- intellij-idea - Intellij IDEA 未在项目中显示 src 文件夹
- web-services - GPS 跟踪器到自定义 Web 服务
- linux - pageup 和 pagedown 在使用 konsole 的 vim 中不起作用
- java - Hibernate:如何将“具有”子类的类映射到单个表?
- android - 是否可以在 Android Emulator 文件系统(在我的计算机内)中搜索文件?
- angular - Angular:如果我们将 .js 或 .ts 放在 import 语句的末尾,则依赖注入不会正确发生
- c# - 由于传递依赖,提供运行时标识符时,Dotnet 还原失败
- r - 提取 1:1000 中从第一个数字开始的所有数字==2