PyQt5 Button Creation with Click Event

  • Share this:

Code introduction


Create a button with the text 'Click Me'. When the button is clicked, it will print out the message 'Button was clicked!'


Technology Stack : PyQt5

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
from PyQt5.QtWidgets import QApplication, QPushButton, QWidget

def create_random_button():
    app = QApplication([])
    widget = QWidget()
    button = QPushButton('Click Me', widget)
    button.setGeometry(50, 50, 100, 50)
    widget.setGeometry(300, 300, 200, 200)
    widget.show()
    button.clicked.connect(lambda: print('Button was clicked!'))
    app.exec_()

# JSON Explanation                
              
Tags: