Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
499 views
in Technique[技术] by (71.8m points)

python - Error lambda missing 1 required positional argument when using with QPushButton

This is entire my code:

import sys

from PySide2.QtCore import Qt
from PySide2.QtWidgets import (
    QApplication,
    QHBoxLayout,
    QLabel,
    QMainWindow,
    QPushButton,
    QVBoxLayout,
    QWidget,
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        v = QVBoxLayout()
        h = QHBoxLayout()

        for a in range(10):
            button = QPushButton(str(a))
            button.clicked.connect(lambda checked, a=a: self.button_clicked(a)) # error here

            h.addWidget(button)

        v.addLayout(h)

        self.label = QLabel("")
        v.addWidget(self.label)
        
        w = QWidget()
        w.setLayout(v)

        self.setCentralWidget(w)

    def button_clicked(self, n):
        self.label.setText(str(n))

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

When I run this code, I get a window like this:image here


Below the buttons, there is a QLabel, and I want when I click on any button, the button's label will refer to this QLabel, but I get a bunch of confusing errors in the terminal. What's wrong with my code, help me, thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The clicked signal is overload so it accepts 2 signatures where it can send a bool or not. The default signature depends on the library, in this case it seems that PySide2 by default does not send the "checked" parameter, unlike PyQt5 that does.

The solution is to indicate the signature:

button.clicked[bool].connect(lambda checked, a=a: self.button_clicked(a))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...