PyQt5 – Toggle Button

In PyQt5 a toggle button is basically is the push button in a special state. Push button is a button when we press it do some task and get back to the normal state it is similar to key board key when we press it, it do some thing and when we release it, it comes back to its original form.

ToggleButton is a type of push button, but it has two states i.e on and off when we press it, it don’t comes back to the original state. Toggle button is similar to a electricity switch when we press it, it remains on and when we turn it off it remains in off position.

In order to create toggle button we have to do the following:

  1. Create a push button.
  2. Set checkable to True i.e if it get pressed it get checked and if it get pressed again it get unchecked similar to check box.
  3. Set calling method which get called when button is pressed.
  4. In calling method check if the button is checked or not.
  5. If button is checked change its color else set the default color to it.

Below is the implementation.





# importing the required libraries
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import * 
import sys
class Window(QMainWindow):
    def __init__(self):
        # set the title
        # setting geometry
        self.setGeometry(100, 100, 600, 400)
        # creating a push button
        self.button = QPushButton("Toggle", self)
        # setting geometry of button
        self.button.setGeometry(200, 150, 100, 40)
        # setting checkable to true
        # setting calling method by button
        # setting default color of button to light-grey
        self.button.setStyleSheet("background-color : lightgrey")
        # show all the widgets
    # method called by button
    def changeColor(self):
        # if button is checked
        if self.button.isChecked():
            # setting background color to light-blue
            self.button.setStyleSheet("background-color : lightblue")
        # if it is unchecked
            # set background color back to light-grey
            self.button.setStyleSheet("background-color : lightgrey")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app


Output :

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.