如何快速改变按钮的颜色

How to change color of a button fast

我正在构建一个测验应用程序,我希望在用户回答问题后,正确的答案会变成绿色,另一个会变成红色,return 之后会变成正常

我尝试使用 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()

我预计颜色会更改为Red/Green一小段时间然后return变为正常等等

您的 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):