NESIA
NESIA

Reputation: 13

On Kivy's Clock, I want Change the Label color

I want to change text color by passing the time. I use Python and kivy. This is my code.In this code, only a label come on.

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.clock import Clock
import random

class MyLabel(Label):
    def callback(self, *arg):
        self.evt = Clock.schedule_interval(self.callback, 1)

    def on_value(self, *arg):
        self.parent.lbl.color = random.choice(['red','blue','black'])


class MyApp(App):
    def build(self):
        layout=BoxLayout()
        layout.lbl = Label(text='NESIA')
        layout.add_widget(layout.lbl)
        return layout

MyApp().run()

`

Upvotes: 0

Views: 233

Answers (1)

Mihai Chelaru
Mihai Chelaru

Reputation: 8187

You never call the on_value() method you define. What you can do is use Clock.schedule_interval() when you build the app, passing in the method that changes the label's colour and the interval in which you want it to be called like so:

from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
from kivy.uix.boxlayout import BoxLayout
import random

class MyLabel(Label):
    def change_color(self, *args):
        r, g, b = random.choice([[1, 0, 0],[0,0,1],[ 1, 1, 1]])
        self.color = [r, g, b, 1]

class MyApp(App):
    def build(self):
        layout = BoxLayout()
        label = MyLabel(text='NESIA')
        Clock.schedule_interval(label.change_color, 1)
        layout.add_widget(label)
        return layout

MyApp().run()

This is assuming what you want is to have a label with the text NESIA whose colour is randomly set to red, blue, or black every second. Note that it's possible that random.choice() returns the same colour twice in a row, meaning it will look like it's not changing for however many seconds that happens for.

Upvotes: 1

Related Questions