Saturday, September 6, 2025
HomeLanguagesPyQt5 – How to access content of label ?

PyQt5 – How to access content of label ?

We can create label using QLabel() method, and set the content using setText() method. In this article, we will see how to access the content of the label, in order to do this we will use text() method.

Syntax : label.text()

Argument : It takes no argument.

Return : It returns a string.

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 geometry
        self.setGeometry(100, 100, 600, 400)
  
        # creating a label widget
        self.label_1 = QLabel("old label ", self)
  
        # setting up the border and background color
        self.label_1.setStyleSheet("border :3px solid black; 
                                    background : pink")
  
        # getting the content of label
        content = self.label_1.text()
          
        # printing the content of label
        print(content)
  
        # moving the label
        self.label_1.move(10, 100)
  
        # creating a new label widget
        self.label_2 = QLabel("new Label ", self)
  
        # setting up the border and background color
        self.label_2.setStyleSheet("border :3px solid black; 
                                    background : green")
  
        # moving the label
        self.label_2.move(110, 110)
          
        # printing the content of label
        print(self.label_2.text())
  
        # 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 :

old label 
new Label 

RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS