In this PyQt5 article we want to learn about How to Create QPushButton in PyQt5, PyQt5 is powerful and popular library for creating desktop applications with Python, there are different widgets in PyQt5, in this article we want to talk about QPushButton.
First of all we need to install PyQt5, for the installation you can use pip.
1 |
pip install PyQt5 |
First of all we need to import the required classes and modules from PyQt5.
1 2 |
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton import sys |
After that we need to create an instance of the QApplication class, which represents our application. This class manages the GUI event loop and handles application-wide settings. Add the following code.
1 |
app = QApplication(sys.argv) |
In PyQt5 QMainWindow is the main window container in PyQt5. we will create an instance of this class and set its properties as needed.
1 2 3 |
window = QMainWindow() window.setWindowTitle("QPushButton Tutorial") window.setGeometry(100, 100, 400, 200) # Set window position and size |
This code is used for creating QPushButton, also we have set the x,y, width and height of the button.
1 2 |
button = QPushButton("Click Me", window) button.setGeometry(100, 50, 200, 50) |
To make our QPushButton interactive, we can connect a function to its clicked signal. This function will be executed whenever the button is clicked.
1 2 3 4 |
def button_clicked(): label.setText("Welcome to geekscoders.com") button.clicked.connect(button_clicked) |
And lastly we need to show the main window and start the application’s event loop.
1 2 |
window.show() sys.exit(app.exec_()) |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel import sys def button_clicked(): label.setText("Welcome to geekscoders.com") app = QApplication(sys.argv) window = QMainWindow() window.setWindowTitle("QPushButton Tutorial") window.setGeometry(100, 100, 400, 200) button = QPushButton("Click Me", window) button.setGeometry(100, 50, 200, 50) button.clicked.connect(button_clicked) label = QLabel(window) label.setGeometry(100, 120, 200, 30) window.show() sys.exit(app.exec_()) |
Run the code and this will be the result
