我最多可以更改按钮的背景多少次? [英] How many times the most I can change the background of the pushButton?

查看:48
本文介绍了我最多可以更改按钮的背景多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图用我通过的颜色和白色之间的颜色闪烁按钮.而且它似乎只是在代码崩溃后才闪烁这么多次.我试过用不同的眨眼率来实现眨眼,它过一段时间它还会坏吗.

So , I am trying to blink the push button with the color that I pass and between white. And it only seems to blink it so many times after that code would crash. I have tried it to implement the blinking with different blink rates and it would it still break at some time.

  • 在'a'中,我有这样的字符串背景颜色:rgb(255,0,0)".
  • 在时间"中,我有一个类似 [208, 280] 的列表,也可能是 [48,32,48,32,100,280],这表示打开和关闭时间第零索引"表示打开,索引 1"表示关闭时间并遵循模式等.
while True:
    i = 0
    while i < len(timings):
        if self.p[2] == 1:
            self.b.setStyleSheet("{}".format(a))
            self.b.update()
            time.sleep(timings[i]/1000)
            self.b.setStyleSheet("Background-color: rgb(255,255,255)")
            self.b.update()
            time.sleep(timings[i+1]/1000)
            i = i + 2

self.head1, self.head2, self.head3 都有类似这样的列表 ["Background-color:rgb(255,0,0)",list of on and off patterns, head number#]

self.head1, self.head2, self.head3 all have list with some thing like this ["Background-color:rgb(255,0,0)",list of on and off patterns, head number#]

现在,我正在处理三个头.

right now, I am working with three heads.

def flash(self):
    obj1 = threads(self.head1, self.head1_pb)
    obj2 = threads(self.head2, self.head2_pb)
    obj3 = threads(self.head3, self.head3_pb)
    obj1.start()
    time.sleep(.02)
    obj2.start()
    time.sleep(.02)
    obj3.start()

class threads(Thread):

    def __init__(self, a, pb):
         Thread.__init__(self)
         self.p = a
         self.b = pb

    def run(self):

       a = self.p[0]
       timings = self.p[1]
       print(timings[0])
       while True:
           i = 0
           while i < len(timings):
                if self.p[2] == 1:
                   self.b.setStyleSheet("{}".format(a))
                   self.b.update()
                   time.sleep(timings[i]/1000)
                   self.b.setStyleSheet("Background-color: rgb(255,255,255)")
                   self.b.update()
                   time.sleep(timings[i+1]/1000)
                   i = i + 2
               elif self.p[2] == 2:
                   self.b.setStyleSheet("{}".format(a))
                   self.b.update()
                   time.sleep(timings[i]/1000)
                   self.b.setStyleSheet("Background-color: rgb(255,255,255)")
                   self.b.update()
                   time.sleep(timings[i+1]/1000)
                   i = i + 2
              else:
                   self.b.setStyleSheet("{}".format(a))
                   self.b.update()
                   time.sleep(timings[i]/1000)
                   self.b.setStyleSheet("Background-color: rgb(255,255,255)")
                   self.b.update()
                   time.sleep(timings[i+1]/1000)
                   i = i + 2

推荐答案

你可以根据需要多次更改颜色,问题是你不应该使用耗时的循环或使用 time.sleep() 因为它们阻止生成 GUI 冻结的事件循环.相反,使用 QTimer 调用经常改变颜色的任务.

You can change the color as many times as you want, the problem is that you should not use a time consuming loop or use time.sleep() because they block the eventloop generating the GUI to freeze. Instead, use a QTimer to call the task that changes color every so often.

在以下示例中,创建一个实现您想要的自定义按钮:

In the following example, create a custom button that implements what you want:

from PySide2 import QtCore, QtGui, QtWidgets


class PushButton(QtWidgets.QPushButton):
    def __init__(self, *args, **kwargs):
        super(PushButton, self).__init__(*args, **kwargs)
        self._color = QtGui.QColor("white")
        timer_on = QtCore.QTimer(singleShot=True, timeout=self.on_timeout)
        timer_off = QtCore.QTimer(singleShot=True, timeout=self.on_timeout)
        self._timers = (timer_on, timer_off)
        for timer, function in zip(self._timers, (self.on, self.off)):
            timer.timeout.connect(function)

    def setTime(self, on_time, off_time):
        for t, timer in zip((on_time, off_time), self._timers):
            timer.setInterval(t)

    @QtCore.Slot()
    def on_timeout(self):
        timer = self.sender()
        if timer not in self._timers:
            return
        timer_on, timer_off = self._timers
        another_timer = timer_off if timer is timer_on else timer_on
        another_timer.start()

    def start(self):
        timer_on, _ = self._timers
        timer_on.start()

    def stop(self):
        for timer in self._timers:
            timer.stop()
        self.off()

    def color(self):
        return self._color

    def setColor(self, color):
        if self.color() == color:
            return
        self._color = color

    def on(self):
        self.setStyleSheet(
            """PushButton{ background-color: %s}""" % (self.color().name(),)
        )

    def off(self):
        self.setStyleSheet(
            """PushButton{ background-color: rgb(255,255,255)}"""
        )


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        button = PushButton()
        button.setColor(QtGui.QColor("salmon"))
        button.setTime(208, 280)
        button.start()

        # stop blink in 30 seconds
        # QtCore.QTimer.singleShot(30 * 1000, button.stop)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    w = Widget()
    w.show()
    sys.exit(app.exec_())

另外:

当你注意到你有很多数据时,最好创建一个迭代器来节省内存.考虑到上述情况,我创建了一个 QPushButton,用于从迭代器获取数据.

As you note that you have a lot of data, it is best to create an iterator to save memory. Considering the above I have created a QPushButton that obtains the data from the iterator.

import random
from functools import partial
from PySide2 import QtCore, QtGui, QtWidgets


def generate_data():
    i = 0
    while i < 1000000:
        color_on = random.randint(10, 500)
        color_off = random.randint(10, 500)
        color = QtGui.QColor(*random.sample(range(255), 3))
        yield color_on, color_off, color
        i += 1


class PushButton(QtWidgets.QPushButton):
    def __init__(self, *args, **kwargs):
        super(PushButton, self).__init__(*args, **kwargs)
        self._color = QtGui.QColor("white")
        self._generator = None

        self.m_timer = QtCore.QTimer(
            self, timeout=self.on_timeout, singleShot=True
        )

    def setGenerator(self, generator):
        self._generator = generator

    def start(self):
        self.on_timeout()

    @QtCore.Slot()
    def on_timeout(self):
        try:
            time_on, time_off, color = next(self._generator)
            self.setColor(color)
            self.m_timer.start(time_on + time_off)
            QtCore.QTimer.singleShot(
                time_on, partial(self.setColor, QtGui.QColor("white"))
            )
        except StopIteration:
            self.m_timer.stop()

    def setColor(self, color):
        self.setStyleSheet(
            """PushButton{ background-color: %s}""" % (color.name(),)
        )


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        lay = QtWidgets.QVBoxLayout(self)
        for _ in range(6):
            button = PushButton()
            button.setGenerator(generate_data())
            button.start()
            lay.addWidget(button)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    app.setStyle("fusion")
    w = Widget()
    w.resize(320, 240)
    w.show()
    sys.exit(app.exec_())

这篇关于我最多可以更改按钮的背景多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆