Dynamic Color Changing Button

  • Share this:

Code introduction


This function creates a button that can change its color. When the user clicks the button, a color dialog appears allowing them to select a color which is then applied to the button.


Technology Stack : PyQt5

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def random_color_button():
    from PyQt5.QtWidgets import QPushButton, QApplication, QColorDialog
    from PyQt5.QtCore import Qt
    
    def change_button_color():
        color = QColorDialog.getColor()
        if color.isValid():
            button.setStyleSheet(f'background-color: {color.name()}')
    
    app = QApplication([])
    button = QPushButton("Change Color", clicked=change_button_color)
    button.show()
    app.exec_()                
              
Tags: