尝试简单的QPushButton背景色更改

2024-10-03 11:25:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助创建一个简单的'眨眼'的效果,通过改变一个Q按钮的背景色。我想如果我能在两种颜色之间快速改变背景色,我就能产生这种闪烁效果。然而,虽然我可以将背景色设置为一种颜色,但我不知道如何在这两种颜色之间快速切换。我尝试使用循环,但我的输出GUI只保留一种颜色。我是这类东西的初学者,所以也许我错过了一个简单的解决方案

我有所有必要的软件包和一切,所以我只包括按钮的一部分,为简单的背景色处理,这是我相信我的问题所在

self.powerup_button = QtWidgets.QPushButton(self.centralwidget)

count = 0

while count < 100:


   self.powerup_button.setStyleSheet("background-color: none")
   count = count + 1

   self.powerup_button.setStyleSheet("background-color: green")
   count = count + 1

我以为while循环会使按钮在两种颜色之间切换,产生我想要的闪烁效果,但我错了


Tags: self颜色countguibutton解决方案按钮color
1条回答
网友
1楼 · 发布于 2024-10-03 11:25:18

试试看:

import sys
from PyQt5 import QtWidgets, QtCore

class MyWindow(QtWidgets.QMainWindow): 
    def __init__(self):
        super().__init__()

        self.flag = True

        self.powerup_button = QtWidgets.QPushButton("Button")
        self.setCentralWidget(self.powerup_button)

        timer = QtCore.QTimer(self, interval=1000)
        timer.timeout.connect(self.update_background)
        timer.start()  

    def update_background(self):
        if self.flag:
            self.powerup_button.setStyleSheet("background-color: none;")
        else:
            self.powerup_button.setStyleSheet("background-color: green;")  
        self.flag = not self.flag            


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    myWindow = MyWindow()
    myWindow.show()
    app.exec_()       

enter image description here

相关问题 更多 >