from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QGridLayout
from PyQt5.QtGui import QColor
from PyQt5.QtCore import QTimer
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.grid_layout = QGridLayout()
self.labels = []
for i in range(9):
label = QLabel()
label.setStyleSheet("background-color: red")
self.labels.append(label)
self.grid_layout.addWidget(label, i // 3, i % 3)
self.setLayout(self.grid_layout)
self.timer = QTimer()
self.timer.timeout.connect(self.change_color)
self.timer.start(100) # 1秒钟变换一次颜色
self.current_index = 0 # 当前标签索引
def change_color(self):
# 重置所有标签为红色
for label in self.labels:
label.setStyleSheet("background-color: red")
# 设置当前索引的标签为绿色
current_label = self.labels[self.current_index]
current_label.setStyleSheet("background-color: green")
# 更新索引
self.current_index = (self.current_index + 1) % len(self.labels)
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()