PyQt Button Click Event Example

  • Share this:

Code introduction


Create a simple PyQt window with a button. When the button is clicked, a message will be printed to the console.


Technology Stack : PyQt5, QWidget, QVBoxLayout, QPushButton, QApplication, sys

Code Type : Function

Code Difficulty : Intermediate


                
                    
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
import sys

def create_button_widget():
    app = QApplication(sys.argv)
    window = QWidget()
    layout = QVBoxLayout()
    
    button = QPushButton("Click Me")
    button.clicked.connect(lambda: print("Button was clicked!"))
    
    layout.addWidget(button)
    window.setLayout(layout)
    window.show()
    
    sys.exit(app.exec_())

# JSON explanation