如何快速更改按钮的颜色

时间:2019-06-02 12:32:46

标签: button kivy kivy-language

我正在构建一个测验应用程序,我希望在用户回答以下问题后,正确的answear将变为绿色,另一个变为红色并随后恢复正常

我尝试使用Time.sleep()方法,但只处理了一次,GUI完全没有改变

     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()

我希望颜色会在短时间内变为红色/绿色,然后恢复正常,依此类推

1 个答案:

答案 0 :(得分:0)

您的success()方法会更改background_color,然后调用get_new_question(),这会将background_color恢复为正常。通常,当快速连续地对GUI元素进行一系列更改时,只会显示最后一个,因此在这种情况下,您将看不到任何更改。另外,在主线程上调用Time.sleep()只会导致延迟,但不允许显示颜色更改。

我建议使用类似的方式将您的通话更改为self.get_new_question()

Clock.schedule_once(self.get_new_question, 0.5)

这会将呼叫self.get_new_question()的时间延迟半秒,因此您应该看到颜色发生了变化。您还需要将self.get_new_question()的签名更改为

def get_new_question(self, dt):

def get_new_question(self, *args):