Tıklandığında belirli aralıklarla rengi değişen buton

Merhaba, butona tıklanınca 0.7 saniye aralıklarla renginin değişmesini istiyorum, fakat yapamadım, aralara self.show koyunca da işe yaramadı, ne yapabilirim???

How to Schedule an Action With Tkinter after() method (pythontutorial.net)

Şöyle bir örnek var.

Der ki.

  • First, the color of the button turns to red.
  • Then, program sleeps for 3 seconds.
  • Finally, the color of the button turns to black.

Her halde buradan kodu devşirebilirsiniz.

Şöyle örnek bir kod paylaşayım.

from PySide2.QtWidgets import *
from PySide2.QtCore import *
from PySide2.QtGui import *
from threading import Thread
from random import randint
from time import sleep
import sys


class GUI(QMainWindow):
    def __init__(self):
        super().__init__()

        self.condition = False
        
        self.setFixedSize(QSize(500, 500))
        self.setWindowTitle("Renk Değiştiren Buton")
        self.show()

        self.button = QPushButton(self, text="Bana Tıkla")
        self.button.setGeometry(QRect(200, 200, 100, 100))
        self.button.setStyleSheet(f"border: none; background-color: white;")
        self.button.clicked.connect(self.clicked)
        self.button.show()

    def clicked(self):
        # False ise True, True ise False yapalım.
        self.condition = not self.condition

        # Koşul cümleleri ile durumu kontrol edelim.
        if self.condition is True:
            Thread(target=self.change_color_simultaneously).start()
        else:
            self.button.setStyleSheet(f"background-color: white;")

    def change_color_simultaneously(self):
        # self.condition değeri False ise dursun.
        while self.condition is True:
            rgb = self.random_color()
            self.button.setStyleSheet(f"background-color: {rgb};")
            sleep(0.7)

    # self ile işimiz yok, staticmethod kullanalım.
    @staticmethod
    def random_color():
        r = randint(0, 255)
        g = randint(0, 255)
        b = randint(0, 255)
        return f"rgb({r}, {g}, {b})"


app = QApplication(sys.argv)
gui = GUI()
app.exec_()

2 Beğeni

Merhaba, kodunuz çalışıyor fakat kendi programıma eklediğimde (3 kere yapıp bitsin şeklinde koydum), 2-3 saniye bekledikten sonra son seçtiği renge dönüyor (sanırım), yani sleepler arasını okumuyor en son ne gördüyse self.show ile yapıştırıyor (yine sanırım)

Eğer sizin belirlediğiniz renge dönmesini istiyorsanız, döngüden sonra setStyleSheet() ile dilediğiniz rengi verebilirsiniz.

while self.condition is True:
    # bir parça kod
# Bir süre renk değiştirdikten sonra beyaz olmasını istiyoruz.
self.button.setStyleSheet(f"background-color: white;")
1 Beğeni