Python PyQt button click example
Write a Python program that creates a PyQt application with a push button. Display a message when the push button is clicked.
From doc.qt.io:
QApplication Class: The QApplication class manages the GUI application's control flow and main settings.
QWidget Class: The QWidget class is the base class of all user interface objects.
QPushButton Class: The QPushButton widget provides a command button.
QMessageBox Class: The QMessageBox class provides a modal dialog for informing the user or for asking the user a question and receiving an answer.
Sample Solution:
Python Code:
Explanation:
In the exercise above -
- Import the necessary modules from PyQt5.
- Define a slot function named "show_message()" that creates a QMessageBox to display a message when called.
- In the main function, create the PyQt application and the main window.
- Create a "QPushButton" widget labeled "Click me!" and set its geometry (position and size) within the window.
- Connect the clicked signal of the button to the "show_message()" slot using the clicked.connect() method.
- Show the main window using window.show().
- Finally, we start the PyQt application's event loop using app.exec_().
Output:
Flowchart:

Python Code Editor:
Previous: Python PyQt Connecting signals to Slots Home.
Next: Python PyQt button actions example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics