heyt0pe
heyt0pe

Reputation: 550

How to set kivy widget id from Python code file

I need help assigning ids to new kivy widgets that are created from a python function

I've tried :

old = Label(id = 'old')

and :

old = Label()
old.id = 'old'

but it doesn't seem to work because, whenever i try referencing the widgets, it gives me an error

Upvotes: 3

Views: 6340

Answers (3)

Justapigeon
Justapigeon

Reputation: 590

For widgets that are made on the python side dynamically, they will not be found in self.ids. Instead, you have to iterate through self.children to find the id assigned to the widget. For example:

for child in self.children:
    if child.id == 'old':
        print child.text
        print 'Text found.'
        break

Upvotes: 1

John Anderson
John Anderson

Reputation: 38947

@ikolim is correct, but there is a very ugly and not recommended way to accomplish what you want:

import weakref

old = Label()
self.ids.add_widget(old)
self.ids['old'] = weakref.ref(old)

This actually adds the old id to the dictionary (assuming self is the correct container). A better way would be to just keep a reference to the old Label.

Upvotes: 5

ikolim
ikolim

Reputation: 16031

The ways that you have creating id in Python code are correct.

But you cannot reference them using self.ids.old or self.ids['old'] because they don't exist in self.ids. The self.ids dictionary type property contains only all widgets tagged with ids defined inside kv file.

To reference id defined in Python code, in this example use self.old.

Accessing Widgets defined inside Kv lang in your python code

When your kv file is parsed, kivy collects all the widgets tagged with id’s and places them in this self.ids dictionary type property. That means you can also iterate over these widgets and access them dictionary style.

Upvotes: 2

Related Questions