PyQt6 GUI App with Clickable Button and Dynamic Label

  • Share this:

Code introduction


This code creates a simple PyQt6 GUI application with a button and a label. When the button is clicked, the label's text is updated.


Technology Stack : PyQt6, Python

Code Type : PyQt6 GUI application

Code Difficulty : Intermediate


                
                    
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel

def create_random_button():
    app = QApplication(sys.argv)
    window = QWidget()
    layout = QVBoxLayout()
    
    # Create a label and add it to the layout
    label = QLabel("Click the button below:")
    layout.addWidget(label)
    
    # Create a button and add it to the layout
    button = QPushButton("Click Me!")
    layout.addWidget(button)
    
    # Set the layout to the window and show the window
    window.setLayout(layout)
    window.show()
    
    # Connect the button's clicked signal to a slot
    button.clicked.connect(lambda: label.setText("Button clicked!"))
    
    # Start the application's event loop
    sys.exit(app.exec())                
              
Tags: