【问题标题】:For loop, can't assign function call - trying to create variables in for loopFor 循环,无法分配函数调用 - 尝试在 for 循环中创建变量
【发布时间】:2012-12-11 02:31:55
【问题描述】:

所以我正在尝试重新创建这个:

    self.button1 = tkinter.Button(self.user_frame, image = self.image1, state = 'disabled', command = self.press1)
    self.button1.pack(side = 'left')
    self.buttonList.append(self.button1)

    self.button2 = tkinter.Button(self.user_frame, image = self.image2, state = 'disabled', command = self.press2)
    self.button2.pack(side = 'left')
    self.buttonList.append(self.button2)

    self.button3 = tkinter.Button(self.user_frame, image = self.image3, state = 'disabled', command = self.press3)
    self.button3.pack(side = 'left')
    self.buttonList.append(self.button3)

等..直到self.button10。

有了这个:

for x in range [1, 11]:
        self.button(x)=tkinter.Button(self.user_frame, image=self.image(x), state = 'disabled', command = self.press(x))
        self.button(x).pack(side='left')
        self.buttonList.append(self.button(x))

我收到语法错误:无法分配给函数调用。我知道这与我如何命名按钮有关,但我无法弄清楚。有什么建议吗?

【问题讨论】:

  • 你可能想看看setattr,它可以让你以你所说的方式声明变量(我没有任何 Tkinter 经验,所以我不确定是否有一个更适合该环境的解决方案。
  • 只需使用按钮对象列表。

标签: python loops for-loop assign


【解决方案1】:

您有大量的语法错误。不是range [1, 11],是range(1, 11)。 您不能分配给self.button(x) - 尝试使用参数x 调用函数self.button

为什么不直接使用按钮列表?这会简单得多。

无论如何,请使用self.__setattr__("button" + str(x), <the new button>)之类的东西

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多