How To Set Id Of Dynamic Textinput In Kivy
Solution 1:
The ids
are setup when your .kv
file (or string) is first processed and is not updated after that. So your new TextInput
widget id does not get added to the ids
. You can work around that by doing:
import weakref
textinput = TextInput(text='123')
self.ids.UpdateCustomer1.add_widget(textinput)
self.ids['AddUserTextBox'] = weakref.ref(textinput)
The weakref
is used because that is what kivy uses when it initially sets up the ids
dictionary. This is not the best way to do it. It would be better just to keep a reference to your added TextInput
.
Solution 2:
Problem
You cannot reference by using self.ids.AddUserTextBox.text
or self.ids['AddUserTextBox'].text
because the id
created in Python code is not the same as id
defined in kv file. The differences are as follow:
- Python code: The value assigned to
id
is a string and it is not stored inself.ids
dictionary. - kv file: The value assigned to
id
is a string and it is stored inself.ids
dictionary.
Kv language » Referencing Widgets
Warning
When assigning a value to id, remember that the value isn’t a string. There are no quotes: good -> id: value, bad -> id: 'value'
Kv language » 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.
Solution
Please refer to snippets, example, and output for details.
- Instantiate a TextInput widget and assign it to
self.AddUserTextBox
- Add
self.AddUserTextBox
widget toself.ids.UpdateCustomer1
- Referencing TextInput's text by
self.AddUserTextBox.text
orroot.AddUserTextBox.text
. Depending on where it was created.
Snippets
self.AddUserTextBox = TextInput(text='123')
self.ids.UpdateCustomer1.add_widget(self.AddUserTextBox)
...
print(self.AddUserTextBox.text)
Example
main.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
classRootWidget(BoxLayout):
defadd_user_text(self):
self.AddUserTextBox = TextInput(text='123')
self.ids.UpdateCustomer1.add_widget(self.AddUserTextBox)
print(self.AddUserTextBox.text)
classTestApp(App):
defbuild(self):
return RootWidget()
if __name__ == "__main__":
TestApp().run()
test.kv
#:kivy 1.11.0<RootWidget>:orientation:'vertical'Button:size_hint:1,0.2text:'Add User TextInput'on_release:root.add_user_text()GridLayout:id:UpdateCustomer1rows:1
Post a Comment for "How To Set Id Of Dynamic Textinput In Kivy"