PyQt5 – 如何改变标签的颜色?
在 PyQt5 中创建 Label 时,我们可以看到没有背景颜色。在本文中,我们将了解如何为标签添加背景颜色。
为了给标签添加边框,我们将使用label.setStyleSheet()
方法,这将为标签添加背景颜色,就像设计 CSS 样式表一样。
Syntax : label.setStyleSheet(“background-color: cyan”)
Argument : It takes string as argument.
Action performed: It changes the background color of the label.
代码 :
# importing the required libraries
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
# set the title
self.setWindowTitle("Label")
# setting the geometry of window
self.setGeometry(0, 0, 400, 300)
# creating a label widget
# by default label will display at top left corner
self.label_1 = QLabel('Light green', self)
# moving position
self.label_1.move(100, 100)
# setting up background color
self.label_1.setStyleSheet("background-color: lightgreen")
# creating a label widget
# by default label will display at top left corner
self.label_2 = QLabel('Yellow', self)
# moving position
self.label_2.move(100, 150)
# setting up background color and border
self.label_2.setStyleSheet("background-color: yellow;
border: 1px solid black;")
# 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())
输出 :