Reputation: 3
Very simple question I might just not be comprehending life,
self.ids.UpdateCustomer1.add_widget(TextInput(text='123',id=str('AddUserTextBox')))
Here is my code, I just want to set the id of a dynamic text box that pops up when a button is pressed. that all works fine, but whenever I reference AddUserTextBox.text it tells me its non-existent. or more specifically " NameError: name 'AddUserTextBox' is not defined"
Now I have tried setting id='AddUserTextBox' and also as id=AddUserTextBox and I have had no luck. all help would be greatly appreciated
Upvotes: 0
Views: 3291
Reputation: 16041
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:
id
is a string and it is not stored in self.ids
dictionary.id
is a string and it is stored in self.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.
Please refer to snippets, example, and output for details.
self.AddUserTextBox
self.AddUserTextBox
widget to self.ids.UpdateCustomer1
self.AddUserTextBox.text
or root.AddUserTextBox.text
. Depending on where it was created. self.AddUserTextBox = TextInput(text='123')
self.ids.UpdateCustomer1.add_widget(self.AddUserTextBox)
...
print(self.AddUserTextBox.text)
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
class RootWidget(BoxLayout):
def add_user_text(self):
self.AddUserTextBox = TextInput(text='123')
self.ids.UpdateCustomer1.add_widget(self.AddUserTextBox)
print(self.AddUserTextBox.text)
class TestApp(App):
def build(self):
return RootWidget()
if __name__ == "__main__":
TestApp().run()
#:kivy 1.11.0
<RootWidget>:
orientation: 'vertical'
Button:
size_hint: 1, 0.2
text: 'Add User TextInput'
on_release:
root.add_user_text()
GridLayout:
id: UpdateCustomer1
rows: 1
Upvotes: 1
Reputation: 39152
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
.
Upvotes: 3