I know many of you are just looking for some reference code to copy so I put that here at the top, but if you want to learn more, a detailed explanation can be found in the video above and in the text below.

import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
                             QVBoxLayout, QWidget, QLabel)
from PyQt5.QtGui import QIcon


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        main_layout = QVBoxLayout()

        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)

        self.count = 0
        self.label = QLabel(str(self.count))
        main_layout.addWidget(self.label)

        self.button_1.clicked.connect(self.button_1_pressed)

        # Toggle button
        self.button_2 = QPushButton("Disable button 1")
        self.button_2.setCheckable(True)
        self.button_2.clicked.connect(self.button_2_pressed)
        main_layout.addWidget(self.button_2)

        # Image Attribution:
        # Play button image created by Freepik 
        # - Flaticon: www.flaticon.com/free-icon/play-button-arrowhead_27223
        self.button_3 = QPushButton()
        icon = QIcon("play-button-arrowhead.png")
        self.button_3.setIcon(icon)
        main_layout.addWidget(self.button_3)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def button_1_pressed(self):
        self.count += 1
        self.label.setText(str(self.count))

    def button_2_pressed(self):
        if self.button_2.isChecked():
            self.button_2.setText("Enable button 1")
            self.button_1.setEnabled(False)
        else:
            self.button_1.setEnabled(True)
            self.button_2.setText("Disable button 1")

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

play-button-arrowhead.png to download:

Play button image created by Freepik – Flaticon: www.flaticon.com/free-icon/play-button-arrowhead_27223

Boilerplate Code

For us to work with QPushButtons, we will need to setup a window to quickly do that. The code for which can be found below:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        
        main_layout = QVBoxLayout()
        
        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

Starting off at the top, we have some imports for the things we will need.

Lines 4-7, subclass QMainWindow in order to allow us to create our own custom main window to add content to. Then it initializes the class by running the super class’ init() method, and setting the title for the window to "My QPushButton Window".

Line 9 created a QVBoxLayout. Lines 11-13 create a widget, adds the layout to that widget and sets it as the central widget for this application.

If you haven’t worked with layouts before, I should have a tutorial up soon covering them, but for now all you really need to know is that this line, and the lines below it make it so you can add widgets (like labels and push buttons) to your interface so that they are stacked vertically and stretch nicely when the window is resized.

Lines 16-20 define the main() function which creates an application initialized with the given command line arguments (sys.argv), creates a main window from our custom class, shows the window, and executes the application.

Lastly, lines 23 and 24 runs the main() function if this is the main file being run.

If you save the file and run it, it should look like this:

Now let’s push some buttons!

Creating a QPushButton

Starting off, we need to update line 2 to import QPushButton:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,   
                             QPushButton)

On line 12 we are going to create a QPushButton in the variable self.button_1, passing it "Button 1" to set its text. Then, on line 13 we add it to the layout.

        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)

Click here for the full code example…
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,   
                             QPushButton)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        
        main_layout = QVBoxLayout()
        
        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)
        
        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

Note, if we push the button, nothing happens. But that is what we are going to get to next.

Button Callback

To show that the button is doing something, we are going to add a QLabel that will show how many times the button is pressed. If you are new to QLabels or need a refresher, I have a full tutorial on QLabels which can be found here.

Up at the top we add an import to QLabel:

from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,   
                             QPushButton, QLabel)

On line 16, we create the variable to track how many times the button was pressed. On line 17 and 18, we create the label, setting the text to be the count, and add it to the layout.

Then on line 20, we tell the program what what function should be called when self.button_1 is clicked. In this case it is self.button_1_pressed as seen below:

        self.count = 0
        self.label = QLabel(str(self.count))
        main_layout.addWidget(self.label)
        
        self.button_1.clicked.connect(self.button_1_pressed)

We haven’t defined that function so we do it below the __init__ method on line 26. There we just increase the count and update the label’s text to be the updated count:

    def button_1_pressed(self):
        self.count += 1
        self.label.setText(str(self.count))

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,   
                             QPushButton, QLabel)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        
        main_layout = QVBoxLayout()
        
        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)
        
        self.count = 0
        self.label = QLabel(str(self.count))
        main_layout.addWidget(self.label)
        
        self.button_1.clicked.connect(self.button_1_pressed)
        
        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def button_1_pressed(self):
        self.count += 1
        self.label.setText(str(self.count))
        

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

And if we push the button, the count is updated!

Toggle or Checkable Buttons

Sometimes you want a button that has two states. Qt calls them checkable buttons and I call them toggle buttons. Let’s see an example of these, and while we are at it I will show you how to update the text of a button. We will create a button that when clicked, will update its own text to show that it is off or on.

Starting off on line 23, we are going to create a new button called self.button_2, setting the text to "Button OFF. Press to turn ON.". Then we are going to make that button checkable by running the function self.button_2.setCheckable() passing it True.

On line 25, we set a callback function for this to self.button_2_pressed, and on line 26, add it to the layout:

        # Toggle button
        self.button_2 = QPushButton("Button OFF. Press to turn ON.")
        self.button_2.setCheckable(True)
        self.button_2.clicked.connect(self.button_2_pressed)
        main_layout.addWidget(self.button_2)

We haven’t defined that function so we do it below the button_1_pressed method on line 36. There we just have an if statement seeing whether the button is checked or not and setting self.button_2‘s text:

    def button_2_pressed(self):
        if self.button_2.isChecked():
            self.button_2.setText("Button ON. Press to turn OFF.")
        else:
            self.button_2.setText("Button OFF. Press to turn ON.")

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,   
                             QPushButton, QLabel)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        
        main_layout = QVBoxLayout()
        
        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)
        
        self.count = 0
        self.label = QLabel(str(self.count))
        main_layout.addWidget(self.label)
        
        self.button_1.clicked.connect(self.button_1_pressed)
        
        # Toggle button
        self.button_2 = QPushButton("Button OFF. Press to turn ON.")
        self.button_2.setCheckable(True)
        self.button_2.clicked.connect(self.button_2_pressed)
        main_layout.addWidget(self.button_2)
        
        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def button_1_pressed(self):
        self.count += 1
        self.label.setText(str(self.count))
    
    def button_2_pressed(self):
        if self.button_2.isChecked():
            self.button_2.setText("Button ON. Press to turn OFF.")
        else:
            self.button_2.setText("Button OFF. Press to turn ON.")
        

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

And if we push the bottom button, the button is toggled and the text is updated:

Disabling Buttons

It can sometimes be necessary to disable buttons so that is what I am going to show you next.

Starting off, we are going to update line 23, so that the button says “Disable button 1”.

        self.button_2 = QPushButton("Disable button 1")

Then we are going to update the self.button_2’s callback function to be the following:

    def button_2_pressed(self):
        if self.button_2.isChecked():
            self.button_2.setText("Enable button 1")
            self.button_1.setEnabled(False)
        else:
            self.button_1.setEnabled(True)
            self.button_2.setText("Disable button 1")

When the button is checked we update the button 2 text to say "Enable button 1" and disable button 1 by running self.button_1.setEnabled() passing it False.

Similarly, when it is not checked we update the text to say "Disable button 1" and enable button 1 by running self.button_1.setEnabled() passing it True.

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QVBoxLayout, QWidget,   
                             QPushButton, QLabel)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        
        main_layout = QVBoxLayout()
        
        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)
        
        self.count = 0
        self.label = QLabel(str(self.count))
        main_layout.addWidget(self.label)
        
        self.button_1.clicked.connect(self.button_1_pressed)
        
        # Toggle button
        self.button_2 = QPushButton("Disable button 1")
        self.button_2.setCheckable(True)
        self.button_2.clicked.connect(self.button_2_pressed)
        main_layout.addWidget(self.button_2)
        
        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def button_1_pressed(self):
        self.count += 1
        self.label.setText(str(self.count))
    
    def button_2_pressed(self):
        if self.button_2.isChecked():
            self.button_2.setText("Enable button 1")
            self.button_1.setEnabled(False)
        else:
            self.button_1.setEnabled(True)
            self.button_2.setText("Disable button 1")
        

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

And if we push the bottom button, button 1 is disabled:

Adding Images to Buttons

Lastly, I am going to show you how to add images to QPushButtons.

Starting off, on line 4, we are going to add a new import to QIcon

from PyQt5.QtGui import QIcon

Then on line 28, we are going to create a new button, self.button_3, without passing in any text.

We then create a QIcon passing it in the path to the image we are using. We then set the icon for the button with the self.button_3.setIcon() method passing it in the icon we created, and we add the button to the layout:

        # Image Attribution:
        # Play button image created by Freepik 
        # - Flaticon: www.flaticon.com/free-icon/play-button-arrowhead_27223
        self.button_3 = QPushButton()
        icon = QIcon("play-button-arrowhead.png")
        self.button_3.setIcon(icon)
        main_layout.addWidget(self.button_3)

The image I use in this example is below. Save it as play-button-arrowhead.png wherever you are running your code from.

Play button image created by Freepik – Flaticon: www.flaticon.com/free-icon/play-button-arrowhead_27223

Click here for the full code example…
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton,
                             QVBoxLayout, QWidget, QLabel)
from PyQt5.QtGui import QIcon


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My QPushButton Window")
        main_layout = QVBoxLayout()

        self.button_1 = QPushButton("Button 1")
        main_layout.addWidget(self.button_1)

        self.count = 0
        self.label = QLabel(str(self.count))
        main_layout.addWidget(self.label)

        self.button_1.clicked.connect(self.button_1_pressed)

        # Toggle button
        self.button_2 = QPushButton("Disable button 1")
        self.button_2.setCheckable(True)
        self.button_2.clicked.connect(self.button_2_pressed)
        main_layout.addWidget(self.button_2)

        # Image Attribution:
        # Play button image created by Freepik 
        # - Flaticon: www.flaticon.com/free-icon/play-button-arrowhead_27223
        self.button_3 = QPushButton()
        icon = QIcon("play-button-arrowhead.png")
        self.button_3.setIcon(icon)
        main_layout.addWidget(self.button_3)

        widget = QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

    def button_1_pressed(self):
        self.count += 1
        self.label.setText(str(self.count))

    def button_2_pressed(self):
        if self.button_2.isChecked():
            self.button_2.setText("Enable button 1")
            self.button_1.setEnabled(False)
        else:
            self.button_1.setEnabled(True)
            self.button_2.setText("Disable button 1")

def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec()


if __name__ == '__main__':
    main()

And if we run that code we should get:

And those are the basics of QPushButtons!

Similar Posts