Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

PyQt5 – How to add image in Label background ?

  • Last Updated : 26 Mar, 2020

In this article, we will see how to add background image to a label, By default, when we create a label there is no background image although we can set background color to it.

Sometimes background image is necessary. In order to set a background image we will use setStyleSheet() method.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Syntax : label.setStyleSheet(“background-image : url(image.png)”;)



Argument : It takes string as argument.

Action performed Add background image to a label.

Code :




# importing the required libraries
  
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
  
        # set the title
        self.setWindowTitle("Python")
  
        # setting  the geometry of window
        self.setGeometry(60, 60, 600, 400)
  
  
        # creating a label widget
        self.label_1 = QLabel(self)
  
        # moving position
        self.label_1.move(100, 100)
  
        # setting up the border
        self.label_1.setStyleSheet("border :3px solid blue;")
  
        # setting label text
        self.label_1.setText("no background image")
  
        # creating a label widget
        self.label_2 = QLabel(self)
  
        # moving position
        self.label_2.move(160, 170)
  
        # setting up the border and adding image to background
        self.label_2.setStyleSheet("background-image : url(image.png);
                                              border : 2px solid blue")
  
  
        # setting label text
        self.label_2.setText("with background image")
        self.label_2.resize(100, 50)
  
        # show all the widgets
        self.show()
  
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())

Output :
pyqt-add-backgroud-image




My Personal Notes arrow_drop_up
Recommended Articles
Page :