PyQt5 – How to add image in window ?
In this article, we will see how to add image to a window. The basic idea of doing this is first of all loading the image using QPixmap and adding the loaded image to the Label then resizing the label according to the dimensions of the image, although the resizing part is optional.
In order to use Qpixmap and other stuff we have to import following libraries:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sys
For loading image :
Syntax :
pixmap = QPixmap('image.png')
Argument : Image name if image is in same folder else file path.
For adding image to label :
Syntax :
label.setPixmap(pixmap)
Argument : It takes QPixmap object as argument.
Code :
Python3
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QPixmap
import sys
class Window(QMainWindow):
def __init__( self ):
super ().__init__()
self .acceptDrops()
self .setWindowTitle( "Image" )
self .setGeometry( 0 , 0 , 400 , 300 )
self .label = QLabel( self )
self .pixmap = QPixmap( 'image.png' )
self .label.setPixmap( self .pixmap)
self .label.resize( self .pixmap.width(),
self .pixmap.height())
self .show()
App = QApplication(sys.argv)
window = Window()
sys.exit(App. exec ())
|
Output :
Last Updated :
03 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...