PyQT clicked事件仅在开始时执行,不再工作

2024-09-30 16:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习PyQT并将其与PySide2一起使用。我了解了按钮事件如何与绑定单击事件一起工作,但是,我有一个问题

我的点击事件在启动时随机执行-我也不理解-执行后点击这些QButtons不会调用绑定方法

class StartWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.button_orginial = QPushButton('Show Original')
        self.button_orginial.setStyleSheet("background-color: #4592af; color: black;")
        self.button_prediction = QPushButton('Show Prediction')
        self.button_prediction.setStyleSheet("background-color: #e3c4a8; color: black;")

        self.horizontalLayout = QHBoxLayout()
        self.verticalLayout = QVBoxLayout()

        self.verticalLayout.addWidget(self.button_orginial)
        self.verticalLayout.addWidget(self.button_prediction)

        self.verticalLayout.addLayout(self.horizontalLayout)

        self.button_prediction.clicked.connect(self.ShowPrediction())
        self.button_orginial.clicked.connect(self.ShowOriginal())

        self.InitWindow()


    def InitWindow(self):
        self.setWindowTitle("SmartAlpha")    
        self.setGeometry(500,500,940,360)
        self.setLayout(self.verticalLayout)

    def ShowPrediction(self):
        self.predictImg = QLabel(self)
        self.predictImg.setPixmap(self.genImage("prediction"))
        self.horizontalLayout.addWidget(self.predictImg)
        print("pred clicked")

    def ShowOriginal(self):
        self.showImage = QLabel(self)
        self.showImage.setPixmap(self.genImage("original"))
        self.horizontalLayout.addWidget(self.showImage)
        print("org clicked")

if __name__ == '__main__':
    app = QApplication([])
    window = StartWindow()
    window.setStyleSheet("background-color: black;")
    #window.showFullScreen()
    window.show()
    app.exit(app.exec_())

Tags: selfdef事件buttonwindowcolorblackbackground
1条回答
网友
1楼 · 发布于 2024-09-30 16:21:43

更改此项:

self.button_prediction.clicked.connect(self.ShowPrediction())
self.button_orginial.clicked.connect(self.ShowOriginal())

为此:

self.button_prediction.clicked.connect(self.ShowPrediction)
self.button_orginial.clicked.connect(self.ShowOriginal)

您正在尝试将回调返回的值绑定到clicked信号,这是错误的。这也是程序启动后会触发回调的原因,因为您要求在将回调传递给connect之前对其进行评估

您希望将函数对象绑定到clicked信号

相关问题 更多 >