How to add buttons and labels in PyQt5?

To add buttons and labels in PyQt5, you first need to import the relevant modules.

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel

Next, add buttons and labels in the main window.

class MyWindow(QMainWindow):
    def __init__(self):

        self.setWindowTitle("My Window")
        self.setGeometry(100, 100, 400, 300)

        self.button = QPushButton("Click me", self)
        self.button.setGeometry(150, 50, 100, 30)

        self.label = QLabel("Hello, PyQt5!", self)
        self.label.setGeometry(150, 100, 100, 30)

    def on_button_click(self):
        self.label.setText("Button clicked")

if __name__ == '__main__':
    app = QApplication([])
    window = MyWindow()

In the code above, we have created a main window class called MyWindow, which includes a button and a label. When the button is clicked, it triggers the on_button_click method, which updates the text content of the label. Finally, we create an application object named app and display the main window window.

Leave a Reply 0

Your email address will not be published. Required fields are marked *