PyQt5 – How to add image in Label background ?

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.

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

Argument : It takes string as argument.

Action performed Add background image to a label.

Code :

filter_none

edit
close

play_arrow

link
brightness_4
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())

chevron_right


Output :
pyqt-add-backgroud-image




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.