【问题标题】:Python function not working - TkinterPython函数不起作用 - Tkinter
【发布时间】:2015-04-29 13:12:36
【问题描述】:

我的函数没有给我正确的输出,它不想工作。我不断收到此错误:

TypeError: list indices must be integers, not str

这是我的代码:

    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()

我希望它根据它是什么按钮来显示商店列表中的内容......

【问题讨论】:

  • 我可能没那么聪明......
  • 如果您认为它可以解决您的问题,请accept 回答。它将在整个社区中识别正确的解决方案。这可以通过单击答案旁边的绿色复选标记来完成。请参阅此image 以供参考。干杯。

标签: python list function python-2.7 tkinter


【解决方案1】:

从代码中删除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)

for 循环遍历列表中的 元素 而不是索引!。 python docs 让它更清晰

Python 中的 for 语句与您在 C 或 Pascal 中可能使用的语句有些不同。 Python 的 for 语句迭代任何序列的项目(列表或一个字符串),按照它们在序列中出现的顺序。

另请注意,Button 构造函数中的command 参数将函数作为参数。所以你最好写command = shopping而不是调用command = shopping(i)

【讨论】:

  • 可能也有助于指出command = shopping(i)引起的不可避免的问题
  • @Jkdc 我们不知道shopping的功能是什么!但是最好在上面加上一行!谢谢:)
【解决方案2】:

for i in shop 更改为for i in xrange(shop)

【讨论】:

  • 当我运行 think 时,它说 settings(i) 中的 i 总是等于四......
【解决方案3】:

您必须使用类似 partial 的东西将参数传递给按钮按下调用的函数。请注意,您已将变量“temp”声明为 2 个不同的事物。它起作用的唯一原因是因为第二个声明是在您使用第一个声明之后。另请注意,“按钮”列表不能在函数 showShop() 之外使用,因为它是在该函数中/本地创建的。以下是基于您发布的内容的工作代码。另外,请不要使用“i”、“l”或“O”作为单个数字变量名称,因为它们看起来像数字。

import Tkinter
from functools import partial

def shopping(btn_num):
   print "button number %d pressed" % (btn_num)
   buttons[btn_num]["bg"]="lightblue"

def showShop(buttons):
      top = Tkinter.Tk()
      shop = ["$100 & level 2 - Shotgun", "$250 & level 3 - 5 Grenades",
              "$500 & level 5 - Rocket Launcher"]

      ##buttons = []
      for ctr in range(len(shop)):
        temp = Tkinter.Button(top, height=10, width=100, text = shop[ctr],
               command = partial(shopping, ctr))
        temp.pack()
        buttons.append(temp)
      top.mainloop()

## lists are mutable
buttons=[]  ## not local to the function
showShop(buttons)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多