[Python] How can I get the name of the button that was clicked?

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I am creating a card game in python. I am using PyQt5 to implement the GUI. The cards are basically QPushButtons with large Icons attached to them. I want to get what button was pressed i.e. objectName of the button that was clicked.

    The Buttons are generated in a for loop according to a list that contains the player hand:

    def hand_update(self):
    if begin == 0:
    for card in p1:
    self.new_card = QtWidgets.QPushButton(self.scrollAreaWidgetContents)
    self.new_card.clicked.connect(self.click_card)
    sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
    sizePolicy.setHorizontalStretch(0)
    sizePolicy.setVerticalStretch(0)
    sizePolicy.setHeightForWidth(self.new_card.sizePolicy().hasHeightForWidth())
    self.new_card.setSizePolicy(sizePolicy)
    self.new_card.setMinimumSize(QtCore.QSize(90, 150))
    self.new_card.setMaximumSize(QtCore.QSize(90, 150))
    self.new_card.setText("")
    self.new_card.setIcon(QtGui.QIcon(f"D:/UNO project/card images/{card}.png"))
    self.new_card.setIconSize(QtCore.QSize(90, 150))
    self.new_card.setObjectName(f"{card}")
    self.horizontalLayout.addWidget(self.new_card)
    self.new_card.show()


    I tried using

    self.new_card.clicked.connect(self.click_card)

    and creating a function called click_card():

    def click_card(self):
    print(self.sender.objectName())


    but this just does nothing for a few seconds and then exits without error when I click on a card.

    If I were to print some string inside the function, it seems to work fine. The name of the button never prints for some reason.

    Continue reading...

Compartilhe esta Página