Sil*_*123 0 python tkinter function list python-2.7
我的功能是没有给我正确的输出,它不想工作.我一直收到这个错误:
TypeError: list indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
def showShop(level = level, cash = cash):
top = Tkinter.Tk()
shop = ["$100 & level 2 - Shotgun", "$250 & level 3 - 5 Grenades", "$500 & level 5 - Rocket Launcher"]
buttons = []
for i in shop:
temp = shop[i]
temp = Tkinter.Button(top, height=10, width=100, text = temp, command = shopping(i))
temp.pack()
buttons.append(temp)
top.mainloop()
Run Code Online (Sandbox Code Playgroud)
我希望它根据它是什么按钮显示商店列表中的内容...
temp = shop[i]从代码中删除
for i in shop:
temp = Tkinter.Button(top, height=10, width=100, text = temp, command = shopping(i))
temp.pack()
buttons.append(temp)
Run Code Online (Sandbox Code Playgroud)
该for循环迭代的元素列表,而不是指数!python 文档使它更清晰
Python中的for语句与您在C或Pascal中使用的语句略有不同.而不是总是迭代数字的算术级数(如在Pascal中),或者让用户能够定义迭代步骤和暂停条件(如C),Python的for语句迭代任何序列的项目(列表或字符串),按照它们出现在序列中的顺序.
另请注意,commandButton构造函数中的参数将函数作为参数.所以你最好写command = shopping一下而不是打电话command = shopping(i).