Python 如何使用kivy clock更改按钮的颜色?

Python 如何使用kivy clock更改按钮的颜色?,python,kivy,Python,Kivy,我希望我的程序将按钮中存储的时间与当前时间进行比较。当我运行程序时,如果出现以下错误,按钮应变为黄色,如果“早”,则变为绿色,如果“准时”,则变为红色: honey = float(self.streak_button.id) AttributeError: 'MainApp' object has no attribute 'streak_button' 这是我的代码: class MainApp(App): def build(self): # build() ret

我希望我的程序将按钮中存储的时间与当前时间进行比较。当我运行程序时,如果出现以下错误,按钮应变为黄色,如果“早”,则变为绿色,如果“准时”,则变为红色:

     honey = float(self.streak_button.id)
 AttributeError: 'MainApp' object has no attribute 'streak_button'
这是我的代码:

class MainApp(App):

    def build(self): # build() returns an instance
        self.store = JsonStore("streak.json") # file that stores the streaks:
        Clock.schedule_interval(self.check_streak, 1/30.)

        return presentation


    def check_streak(self, dt):
        honey = float(self.streak_button.id)
        #print(f"\tdelta={honey}")

        # used to give 30 minute grace period
        delay = honey + 1800
        check = False

        if honey > time.time() and honey < delay:
            check = True

        if honey > time.time():
            self.streak_button.color = 0,1,0

        if check == True:
            self.streak_button.color = 0,0,1

        if honey < time.time():
            self.streak_button.color = 1,0,0


使用以下方法更改按钮的颜色:

  • background_normal=''
    #设置素色
  • background_color=[1,0,0,1]
    #背景色,格式为(r,g,b,a)
背景色,格式为(r、g、b、a)

这将作为纹理颜色的倍增。默认纹理 是灰色的,所以只需设置背景色就会显示较暗的颜色 结果。要设置普通颜色,请将设置为“”

参数为a,默认为[1, 1,1,1]

例子 main.py
从kivy.app导入应用
从kivy.uix.screenmanager导入屏幕
从kivy.uix.button导入按钮
从kivy.storage.jsonstore导入jsonstore
从kivy.lang导入生成器
从kivy.clock导入时钟
导入时间
导入json
第二类屏幕(屏幕):
通过
生成器。加载\u字符串(“”)
:
网格布局:
id:条纹区
科尔斯:2
""")
类按钮(按钮):
#rgba=ListProperty([])
def on_触控向下(自身,触控):
如果自碰撞点(*touch.pos):
打印(f“\nCustomButton.on_touch_down:text={self.text}”)
自动发送('在印刷机上')
返回真值
返回超级(条纹按钮,自我)。打开触摸向下(触摸)
类TestApp(应用程序):
def生成(自):
self.store=JsonStore(“streak.json”)
时钟。计划时间间隔(自检时间间隔,1/30)
返回屏幕二()
def检查条纹(自身,dt):
打印(f“\n检查条纹:)
#检查所有按钮
对于反向中的子项(self.root.ids.streak_zone.children):
蜂蜜=浮动(child.id)
打印(f“\tdelta={honey}”)
#用于提供30分钟的宽限期
延迟=蜂蜜+1800
检查=错误
如果蜂蜜>时间。时间()和蜂蜜<延迟:
检查=正确
如果蜂蜜>时间。时间()
打印(“\t\t默认”)
child.background_normal=''
child.background_color=[1,1,0,1]#黄色
elif检查==真:
打印(“\t\t时间”)
child.background_normal=''
child.background_color=[0,1,0,1]#绿色
elif honey
使用以下方法更改按钮的颜色:

  • background_normal=''
    #设置素色
  • background_color=[1,0,0,1]
    #背景色,格式为(r,g,b,a)
背景色,格式为(r、g、b、a)

这将作为纹理颜色的倍增。默认纹理 是灰色的,所以只需设置背景色就会显示较暗的颜色 结果。要设置普通颜色,请将设置为“”

参数为a,默认为[1, 1,1,1]

例子 main.py
从kivy.app导入应用
从kivy.uix.screenmanager导入屏幕
从kivy.uix.button导入按钮
从kivy.storage.jsonstore导入jsonstore
从kivy.lang导入生成器
从kivy.clock导入时钟
导入时间
导入json
第二类屏幕(屏幕):
通过
生成器。加载\u字符串(“”)
:
网格布局:
id:条纹区
科尔斯:2
""")
类按钮(按钮):
#rgba=ListProperty([])
def on_触控向下(自身,触控):
如果自碰撞点(*touch.pos):
打印(f“\nCustomButton.on_touch_down:text={self.text}”)
自动发送('在印刷机上')
返回真值
返回超级(条纹按钮,自我)。打开触摸向下(触摸)
类TestApp(应用程序):
def生成(自):
self.store=JsonStore(“streak.json”)
时钟。计划时间间隔(自检时间间隔,1/30)
返回屏幕二()
def检查条纹(自身,dt):
打印(f“\n检查条纹:)
#检查所有按钮
对于反向中的子项(self.root.ids.streak_zone.children):
蜂蜜=浮动(child.id)
打印(f“\tdelta={honey}”)
#用于提供30分钟的宽限期
延迟=蜂蜜+1800
检查=错误
如果蜂蜜>时间。时间()和蜂蜜<延迟:
检查=正确
如果蜂蜜>时间。时间()
打印(“\t\t默认”)
child.background_normal=''
child.background_color=[1,1,0,1]#黄色
elif检查==真:
打印(“\t\t时间”)
child.background_normal=''
child.background_color=[0,1,0,1]#绿色
elif honeydef display_btn(self):
        # display the names of the streaks in a list on PageTwo
        with open("streak.json", "r") as read_file:
            data = json.load(read_file)

        for value in data.values():
            if value['delta'] is not None:
                print(f"action={value['action']}, delta={value['delta']}")
                self.streak_button = StreakButton(id=str(value['delta']), text=value['action'],
                                            on_press=self.third_screen)
                self.root.screen_two.ids.streak_zone.add_widget(self.streak_button)

background_color
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.button import Button
from kivy.storage.jsonstore import JsonStore
from kivy.lang import Builder
from kivy.clock import Clock

import time
import json


class ScreenTwo(Screen):
    pass


Builder.load_string("""
<ScreenTwo>:
    GridLayout:
        id: streak_zone
        cols: 2
""")


class StreakButton(Button):
    # rgba = ListProperty([])

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print(f"\nCustomButton.on_touch_down: text={self.text}")
            self.dispatch('on_press')
            return True
        return super(StreakButton, self).on_touch_down(touch)


class TestApp(App):
    def build(self):
        self.store = JsonStore("streak.json")
        Clock.schedule_interval(self.check_streak, 1/30.)

        return ScreenTwo()

    def check_streak(self, dt):
        print(f"\ncheck_streak:")

        # check all buttons
        for child in reversed(self.root.ids.streak_zone.children):
            honey = float(child.id)
            print(f"\tdelta={honey}")

            # used to give 30 minute grace period
            delay = honey + 1800
            check = False

            if honey > time.time() and honey < delay:
                check = True

            if honey > time.time():
                print("\t\tearly")
                child.background_normal = ''
                child.background_color = [1, 1, 0, 1]    # Yellow colour

            elif check == True:
                print("\t\ton time")
                child.background_normal = ''
                child.background_color = [0, 1, 0, 1]    # Green colour

            elif honey < time.time():
                print("\t\tlate")
                child.background_normal = ''
                child.background_color = [1, 0, 0, 1]    # Red colour

    def display_btn(self):
        print(f"\ndisplay_btn:")

        with open("streak.json", "r") as read_file:
            data = json.load(read_file)

            for value in data.values():
                if value['delta'] is not None:
                    print(f"action={value['action']}, delta={value['delta']}")
                    streak_button = StreakButton(id=str(value['delta']), text=value['action'], on_press=self.third_screen)
                    self.root.ids.streak_zone.add_widget(streak_button)


if __name__ == '__main__':
    TestApp().run()