In this PyQt5 article we want to learn How to Add Text and Image in PyQt5 Label, so PyQt5 is popular Python library for creating desktop applications, and Label is one of the important widget in PyQt5 that we can use for displaying text or adding images.
First of all if you have not installed PyQt5, you need to install and you can use pip for that.
1 |
pip install PyQt5 |
To start, we need to import the required modules from PyQt5, these are our imports.
1 2 3 |
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel from PyQt5.QtGui import QPixmap import sys |
After that we need to create an instance of the QApplication class to manage the GUI event loop. and than we creates a QMainWindow instance as the main window container, also if you see we have added some methods like setWindowTitle(), it is used for setting the window title, also setGeometry(), it is used for setting the x,y, width and height of the window.
1 2 3 4 5 6 7 8 |
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Label Example") self.setGeometry(100, 100, 400, 300) app = QApplication(sys.argv) window = MainWindow() |
This code is used for creating the label and setting the x,y,width and height of the window.
1 2 |
self.label_text = QLabel("Hello Geekscoders.com", self) self.label_text.setGeometry(100, 50, 200, 30) |
For displaying an image, we need to use the QPixmap class from the QtGui module. this an example that how you can add an image to a QLabel:
1 2 3 4 5 |
self.label_image = QLabel(self) self.label_image.setGeometry(100, 100, 200, 150) pixmap = QPixmap("icon.png") self.label_image.setPixmap(pixmap) |
To display the main window and start the application’s event loop, you can use this code.
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 22 23 24 25 26 |
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel from PyQt5.QtGui import QPixmap import sys class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Label Example") self.setGeometry(100, 100, 400, 300) self.label_text = QLabel("Hello Geekscoders.com", self) self.label_text.setGeometry(100, 50, 200, 30) self.label_image = QLabel(self) self.label_image.setGeometry(100, 100, 200, 150) pixmap = QPixmap("icon.png") self.label_image.setPixmap(pixmap) if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) |
Run the code and this will be the result
