Random Color Changing Button

  • Share this:

Code introduction


This code defines a button that changes its background color to random when clicked. The random color is generated by creating three random bytes, converting each byte to a number between 0-255, and then using these numbers to set the button's background color.


Technology Stack : PyQt6, QPushButton, QColor, os.urandom

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_color_button():
    from PyQt6.QtWidgets import QPushButton
    from PyQt6.QtGui import QColor

    def button_clicked():
        button.setStyleSheet(f"background-color: {QColor(int.from_bytes(os.urandom(2), 'big'), int.from_bytes(os.urandom(2), 'big'), int.from_bytes(os.urandom(2), 'big'))}")

    button = QPushButton("Click for a random color!")
    button.clicked.connect(button_clicked)
    return button