Search code examples
buttonkivykivy-language

How to change color of a button fast


I'm Building a quiz app, I want after the user answer the question that the right answear will become green and the other to red and return to normal afterwards

I tried to use the Time.sleep() method but only made a dealy and the GUI didnt change at all

     def send_answer(self, text):
     return self.success() if text == self.correct else self.end_game()
def get_new_question(self):
        rnd_sql = "SELECT * FROM persons ORDER BY RANDOM() LIMIT 4;"
        four_persons = GAME_DB.execute(rnd_sql, ())
        four_persons_names = [" ".join([person[0], person[1]]) for person in four_persons]
        self.answers = four_persons_names
        rnd_num = random.randrange(0, 4)
        self.correct = four_persons_names[rnd_num]
        print four_persons_names[rnd_num]
        self.pic = CoreImage(io.BytesIO(four_persons[rnd_num][2]), ext=four_persons[rnd_num][3])
        self.ids.main_pic.texture = self.pic.texture
        buttons = ["button_{0}".format(i + 1) for i in range(0, 4)]
        for b in buttons:
            # Return to normal color
            self.ids[b].background_color = [0.2, 0.5, 0.7, 1]
    def success(self):
        self.score += 10
        buttons = ["button_{0}".format(i + 1) for i in range(0, 4)]
        for b in buttons:
            if self.ids[b].text == self.correct:
                #Change to Green
                self.ids[b].background_color = [0, 1, 0, 1]
            else:
                #Change to Red
                self.ids[b].background_color = [1, 0, 0, 1]
        self.get_new_question()

i expected that the color will be changed to Red/Green for a small time and then return to normal and so on


Solution

  • Your success() method changes the background_color, then calls get_new_question(), which changes background_color back to normal. Typically, when a series of changes to a GUI element is made in rapid succession, only the last one will appear, so in this case you will see no change. Also, calling Time.sleep() on the main thread will just cause a delay, but will not allow the color change to be displayed.

    I would suggest changing your call to self.get_new_question() with something like

    Clock.schedule_once(self.get_new_question, 0.5)
    

    This will delay the call to self.get_new_question() by half a second, so you should see the color change. You will also need to change the signature of self.get_new_question() to

    def get_new_question(self, dt):
    

    or

    def get_new_question(self, *args):