James C
James C

Reputation: 919

Initialize Kivy widget values from Python on program start

I am trying to initialize some values of widgets in Kivy on program start, with no success. Simplified Python code is:

inital_text = "init text"

class MainApp(App):

    def initialize_widgets(self):
        self.root.ids.my_label.text = initial_text

if __name__ == '__main__':
    MainApp().run()
    MainApp.initialize_widgets(App)

And the relevant piece from kv file is:

Label:
    id: my_label
    text: "default text" 

When I run the program, the label says "default text". When quitting it, I get the error:

line 5, in initialize_widgets
self.root.ids.my_label.text = initial_text
AttributeError: type object 'App' has no attribute 'root'

I have tried other workarounds, some quite desperate ones, with no success.

Upvotes: 2

Views: 1548

Answers (1)

ikolim
ikolim

Reputation: 16041

Use on_start event to initialize the label's text on program start. In the example below, a Clock.schedule_once event was added to show the initial value and then the change.

Note

In this example, the root widget is Label widget (root) and the root's dictionary (root.ids) is empty. If there is another widget with id: my_textinput, added as children of the root then root's dictionary will contain one id i.e. my_textinput. A print(self.root.ids) will demonstrate this.

self - The keyword self references the “current widget instance” i.e. App.

Kivy Language » ids

When the kv file is processed, weakrefs to all the widgets tagged with ids are added to the root widget’s ids dictionary.

Snippets

from kivy.app import App


initial_text = "init text"


class MainApp(App):

    def on_start(self):
        self.root.text = initial_text


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

Example

main.py

from kivy.app import App
from kivy.clock import Clock

initial_text = "init text"


class MainApp(App):

    def on_start(self):
        Clock.schedule_once(self.initialize_widgets, 5)

    def initialize_widgets(self, dt):
        self.root.text = initial_text


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

Output

Img01 - App Startup Img02 - Label's text changed

Upvotes: 2

Related Questions