Random Color Button Function

  • Share this:

Code introduction


This function creates a button that changes the background color of the button to a random color when it is clicked.


Technology Stack : PyQt5

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color_button(button):
    from PyQt5.QtWidgets import QPushButton
    from PyQt5.QtGui import QColor
    from PyQt5.QtCore import Qt

    def change_color():
        random_color = QColor(Qt.red().lightness() + Qt.green().lightness() + Qt.blue().lightness())
        button.setStyleSheet(f'background-color: {random_color.name()}')

    button.clicked.connect(change_color)                
              
Tags: