Search code examples
pythonkivybuildozer

How to update a kivy label from another class


import kivy
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout


class MyGrid(GridLayout):
    def __init__(self, **kwargs):
        super(MyGrid, self).__init__(**kwargs)
        self.rows = 2
        self.accel  = Label(text = "unknown")
        self.orein = Label(text = "unknown")
        self.add_widget(self.accel)
        self.add_widget(self.orein)

class MyApp(App):
    def build(self):
        return MyGrid()
        Clock.schedule_interval(self.update, 1)

    def update(self, dt):
        ac = "dfskjjlfh"
        ore = "kjdsfkjdf"
        App.accel.text = ac
        App.orein.text = ore

MyApp().run()

I am having trouble finding an answer, to how I can update a Label from an another class. I keep getting the following error:

The following code is unreachable

Both widgets are stuck with the string unknown, but do not change to the variables in the function update.


Solution

  • I have no idea about the error you mentioned :

    The following code is unreachable

    May be the IDLE you are using causes the error (as your posted code will never throw such error).

    However, there's indeed some issues with your code.

    Firstly, in method build you did,

        def build(self):
            return MyGrid()
            Clock.schedule_interval(self.update, 1)
    

    As you return first then schedule a callback, your callback function will never be executed. So you need to switch their order.

    Secondly, in method update you did App.accel.text. This will raise AttributeError as the App class has no such property accel. Moreover it's even not there in the instance of App class (i e. in MyApp). You generally need not to refer the App class directly, rather it's instance (except for some method like get_running_app etc.)

    As it seems you want to access the property of MyGrid in MyApp, create an instance of that class in method build thereby you will be able to access whatever properties you defined in that class. Thus your modified MyApp should now look like,

    class MyApp(App):
        def build(self):
            self.grid = MyGrid() # Creating an instance.
            Clock.schedule_interval(self.update, 1.)
            return self.grid
    
        def update(self, dt):
            ac = "dfskjjlfh"
            ore = "kjdsfkjdf"
            # Now access that instance and its properties.
            self.grid.accel.text = ac
            self.grid.orein.text = ore