问题
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
回答1:
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.
回答2:
@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
.
回答3:
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
来源:https://stackoverflow.com/questions/52151553/how-to-set-kivy-widget-id-from-python-code-file