Skip to main content
 首页 » 编程设计

python之PyQt:获取调用特定功能的按钮

2025年05月04日13shangdawei

我用 PyQt 做了一个多页面应用,一般是问答游戏。

所以现在每当用户犯错或正确回答问题时,它都会调用正确/错误的函数。


错误答案函数:

def incorrect(self): 
    self.pic3.hide() 
    self.que1.hide() 
    self.answ.hide() 
    self.answ1.hide() 
    self.answ2.hide() 
    self.pic4.setGeometry(0, 0, 1280, 800) 
    self.pic4.show() 
    self.goback.show()  
    self.cont = QtGui.QPushButton(self) 
    self.cont.setObjectName('cont') 
    self.cont.setStyleSheet("#cont {background-image: url(':/images/Continue.png'); border: none; }" 
    "#cont:hover { background-image: url(':/images/Continue1.png'); }" 
    "#cont:pressed { background-image: url(':/images/Continue2.png'); }") 
    self.cont.setGeometry(980, 610, 300, 300) 
    self.cont.clicked.connect(self.question2) 
    self.cont.show() 
    self.heart2.hide() 
    #self.heart1.hide() 
    if ( self.heart2.isHidden() and self.heart1.isHidden() ): 
        gameover() 
    else: 
        pass 

所以我要在这个函数中制作多个“cont”小部件,这样做的目的是因为我希望它继续特定的问题(如果用户在问题 1 中失败或成功,它应继续问题 2)。

但为此,应该有一个代码来确定是否从 button1 或 button2 调用错误答案功能,点击时两个按钮连接到同一个插槽,如果它从 button1 调用,它将显示 cont pushbutton,单击时显示 question2 小部件(Question2 页面)。

但是如果它从button2调用,它会显示cont2 pushbutton,点击时会显示问题3页面。

代码应该是这样的:

if self.connected from button1: 
   cont.show() 
if self.connected from button2: 
   cont2.show() 
else: 
    pass 

图片示例:

请您参考如下方法:

使用sender()函数得到一个发送了信号的QObject:

class Example(QMainWindow): 
 
    def __init__(self): 
        super().__init__() 
 
        btn1 = QPushButton("Button 1", self) 
        btn1.clicked.connect(self.buttonClicked) # connect signal to slot 
 
        self.setWindowTitle('Event sender') 
        self.show() 
 
    def buttonClicked(self): 
        sender = self.sender()  # This is what you need 
        self.statusBar().showMessage(sender.text() + ' was pressed')