0
class MainMenu(QWidget):

def __init__(self):
    # QWiget constructor
    super().__init__()
    self.initUI()

def initUI(self):
    self.buttons = (QPushButton('Uebergang'), QPushButton('Scherung'), QPushButton('Wippe'))
    self.layout = QVBoxLayout()

    for button in self.buttons:
        self.layout.addWidget(button)
        func = lambda : self.openMenu(button.text())
        button.clicked.connect(func)

    self.setLayout(self.layout)
    self.show()

def openMenu(self, Menu):
    print(Menu)

When I click on any of the three buttons it always prints "Wippe". I don't understand why. I know this question has been answered before but the answers didn't solve my problem.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Hell stormer
  • 413
  • 1
  • 4
  • 14
  • 1
    Use `partial` or change `func = lambda : self.openMenu(button.text())` to `func = lambda _, text=button.text() : self.openMenu(text)`. Note that you shouldn't use the `text()` property of a button, as Qt might change the text adding mnemonics. – musicamante Apr 06 '20 at 11:53
  • If I change it to func = lambda _, text=button.text() : self.openMenu(text) I get the error: TypeError: () missing 1 required positional argument: '_' when clicking on any button – Hell stormer Apr 06 '20 at 13:08
  • Are you sure you used the lambda exactly as I wrote it? I just tried it *with your code* and it works. – musicamante Apr 06 '20 at 13:29
  • Yeah I guess it doesn't matter that much. partial() works fine thanks :) – Hell stormer Apr 07 '20 at 10:32
  • No, it actually matters: it *should* work, and while lambda and partial are similar approaches, they are *not* identical, and their behavior can be very different with variables. – musicamante Apr 07 '20 at 13:06

0 Answers0