How to read and display images with PyQt5?

In PyQt5, you can use the QPixmap class to load and display images.

Firstly, you need to install the PyQt5 library by using the following command:

pip install PyQt5

Next, you can use the following code to read and display an image.

from PyQt5.QtWidgets import QApplication, QLabel
from PyQt5.QtGui import QPixmap

# 创建应用程序对象
app = QApplication([])

# 创建标签对象
label = QLabel()

# 创建图片对象
pixmap = QPixmap('image.jpg')

# 将图片设置为标签的内容
label.setPixmap(pixmap)

# 显示标签
label.show()

# 运行应用程序
app.exec_()

In the above code, essential classes and modules are first imported. Then, a QApplication object is created to represent the application. Next, a QLabel object is created as a container to display the image. The image file is read using the QPixmap class and set as the content of the QLabel. Finally, the label is displayed by calling the show() method, and the application is run using the app.exec_() method.

Please note that the above code assumes that you have named the image file as image.jpg and placed it in the same directory as the script. If your image file is named differently or located in a different path, please adjust the code accordingly.

bannerAds