Random Color Button Generator with PyQt

  • Share this:

Code introduction


This code creates a PyQt application with a button. Each time the button is clicked, it generates a random color and sets the button's background color to this random color.


Technology Stack : PyQt5, PyQt5.QtWidgets, PyQt5.QtGui, PyQt5.QtCore

Code Type : GUI application

Code Difficulty : Intermediate


                
                    
def random_color_button_clicked():
    from PyQt5.QtWidgets import QPushButton, QApplication, QWidget
    from PyQt5.QtGui import QColor
    from PyQt5.QtCore import Qt

    def generate_random_color():
        return QColor(Qt.qrand() * 255 / 65535, Qt.qrand() * 255 / 65535, Qt.qrand() * 255 / 65535)

    class ColorButton(QWidget):
        def __init__(self):
            super().__init__()
            self.initUI()

        def initUI(self):
            self.setGeometry(300, 300, 280, 170)
            self.setWindowTitle('Random Color Button')

            self.color_button = QPushButton('Click for Random Color', self)
            self.color_button.setGeometry(50, 50, 180, 50)
            self.color_button.clicked.connect(self.change_color)

        def change_color(self):
            color = generate_random_color()
            self.color_button.setStyleSheet(f'background-color: {color.name()}')

if __name__ == '__main__':
    app = QApplication([])
    ex = ColorButton()
    ex.show()
    app.exec_()