0

im trying to make calculator in pyqt5 and I cannot correctly pass numbers to function when button is clicked. This is my code:

        buttons = ['7','8','9','/','MOD','AND','4','5','6','*','Or','Xor','1','2','3','.','Lsh','Not','0','+/-',',','+','=','Int','A','B','C','D','E','F']
        positions = [(i,j) for i in range(5) for j in range(6) ]
        #creating array of buttons
        self.gridButtons = [[0 for x in range(6)] for y in range(5)]
        for position, button in zip(positions,buttons):
            if button.isnumeric():
                print(button)
                self.gridButtons[position[0]] [position[1]] = QPushButton(button, clicked = lambda:self.numberPressed(button))

Problem is when I press the button, it triggers a function but instead of passing appropriate string like '1','2', it passes the last string in buttons array which is 'F'. How can I overcome this?

Cnewbiec
  • 61
  • 8

1 Answers1

1

Your lambda is executed at some time after your loop has run completely. This means that the lambda will always be executed with the last object of the for loop.

To prevent this from happening, you can use a closure. Python has a simple way to create closures: Instead of a lambda use functools.partial

self.gridButtons[position[0]] [position[1]] = QPushButton(button, clicked = functools.partial(self.numberPressed, button))
Tim Woocker
  • 1,883
  • 1
  • 16
  • 29