PyQt5 buttons


PyQt5 supports buttons using the QPushButton class. This class is inside the PyQt5.QtWidgets group. The button can be created by calling the constructor QPushButton with the text to display as parameter.

Related courses
You may like:

Introduction
To use buttons with a PyQt5 application, we need to update our import line:

from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot

In the initUI() method, add these lines of code:

button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)

QPushButton creates the widget, the first argument is text on the button.
The method setToolTip shows the message when the user points the mouse on the button.
Finally the button is moved to the coordinates x=100,y=70.
We need to create a method for a button click:

@pyqtSlot()
def on_click(self):
    print('PyQt5 button click')

Add connect the method to the click with:

button.clicked.connect(self.on_click)

Final PyQt5 button code:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
 
class App(QWidget):
 
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 320
        self.height = 200
        self.initUI()
 
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
 
        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100,70) 
        button.clicked.connect(self.on_click)
 
        self.show()
 
    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

pyqt5-button

Screenshot of PyQt5 button example above.

Download PyQT5 Examples


PyQt5 statusbar
PyQt5 signals and slots