【问题标题】:How can I generate my buttons using a for loop? [duplicate]如何使用 for 循环生成按钮? [复制]
【发布时间】:2019-09-17 00:27:52
【问题描述】:

我正在使用 tkinter 创建一个计算器,并希望最小化按钮的代码。如何在仍然包含 lambda 命令的情况下进行有效的 for 循环?下面是用于创建我的按钮的代码示例

    self.seven = Button(self, text = "7",  width = 10, height = 3, cursor = "hand2", command = lambda: (self.expression(7))).grid(row = 1, column = 0, padx = 1, pady = 1)

    self.eight = Button(self, text = "8",  width = 10, height = 3, cursor = "hand2", command = lambda: (self.expression(8))).grid(row = 1, column = 1, padx = 1, pady = 1)

    self.nine = Button(self, text = "9",  width = 10, height = 3, cursor = "hand2", command = lambda: (self.expression(9))).grid(row = 1, column = 2, padx = 1, pady = 1)

【问题讨论】:

    标签: python for-loop button tkinter calculator


    【解决方案1】:

    您需要将所有按钮存储在list

    self.buttons = []
    for i in range (7, 10):
        self.buttons.append(Button(self, text = str(i),  width = 10, height = 3, cursor = "hand2", command = lambda i=i: (self.expression(i))).grid(row = 1, column = (i - 1) % 3, padx = 1, pady = 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2020-04-11
      • 1970-01-01
      相关资源
      最近更新 更多