PyQt5 – 如何改变主窗口的背景颜色

PyQt5 – 如何改变主窗口的背景颜色

用PyQt创建桌面程序的第一步是让一个窗口显示在你的桌面上,在这篇文章中,我们将看到如何改变这个窗口的颜色。为了改变主窗口的颜色,我们使用setStylesheet()方法。

语法: setStyleSheet(“background-color: gray;”)

参数: 它需要字符串作为参数。

例子 #1 :

# importing the required libraries
  
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore
from PyQt5.QtGui import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # changing the background color to yellow
        self.setStyleSheet("background-color: yellow;")
  
        # set the title
        self.setWindowTitle("Color")
  
        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)
  
        # creating a label widget
        self.label = QLabel("Yellow", self)
  
        # moving position
        self.label.move(100, 100)
  
        # setting up border
        self.label.setStyleSheet("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())

输出:

PyQt5 - 如何改变主窗口的背景颜色?

例子#2

# importing the required libraries
  
from PyQt5.QtWidgets import * 
from PyQt5 import QtCore
from PyQt5.QtGui import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # changing the background color to cyan
        self.setStyleSheet("background-color: cyan;")
  
        # set the title
        self.setWindowTitle("Color")
  
        # setting  the geometry of window
        self.setGeometry(0, 0, 400, 300)
  
        # creating a label widget
        self.label = QLabel("Cyan", self)
  
        # moving position
        self.label.move(100, 100)
  
        # setting up border
        self.label.setStyleSheet("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())

输出 :

PyQt5 - 如何改变主窗口的背景颜色?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程