-1

I'm using tkinter to create a calculator, and want to minimise the code for my buttons. How can I make an efficient for loop with the lambda command still included? Below is an example of the code used to create my buttons

    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)
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685

1 Answers1

0

You need to store all buttons in 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))
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35