Thursday, October 2, 2025
HomeLanguagesPyQt5 QPushButton

PyQt5 QPushButton

QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used.

Example:

A window having a Push Button, when clicked a message will appear “You clicked Push Button”.

Below is the code:




from PyQt5 import QtCore, QtGui, QtWidgets
import sys
  
class Ui_MainWindow(object):
  
    def setupUi(self, MainWindow):
        MainWindow.resize(506, 312)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
          
        # adding pushbutton
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(200, 150, 93, 28))
  
        # adding signal and slot 
        self.pushButton.clicked.connect(self.changelabeltext)
    
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(140, 90, 221, 20))      
  
        # keeping the text of label empty before button get clicked
        self.label.setText("")     
         
        MainWindow.setCentralWidget(self.centralwidget)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
  
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "Push Button"))
          
    def changelabeltext(self):
  
        # changing the text of label after button get clicked
        self.label.setText("You clicked PushButton")    
  
        # Hiding pushbutton from the main window
        # after button get clicked. 
        self.pushButton.hide()   
  
if __name__ == "__main__"
    app = QtWidgets.QApplication(sys.argv) 
    
    MainWindow = QtWidgets.QMainWindow() 
    ui = Ui_MainWindow() 
    ui.setupUi(MainWindow) 
    MainWindow.show()
   
    sys.exit(app.exec_()) 


Output:

Main Window having push button.

After clicking the button message appeared “You clicked Push Button.

RELATED ARTICLES

Most Popular

Dominic
32331 POSTS0 COMMENTS
Milvus
85 POSTS0 COMMENTS
Nango Kala
6703 POSTS0 COMMENTS
Nicole Veronica
11867 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11926 POSTS0 COMMENTS
Shaida Kate Naidoo
6818 POSTS0 COMMENTS
Ted Musemwa
7079 POSTS0 COMMENTS
Thapelo Manthata
6775 POSTS0 COMMENTS
Umr Jansen
6776 POSTS0 COMMENTS