How to set kivy widget id from Python code file

孤街醉人 提交于 2021-01-27 18:47:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!