Dave Brunker Dave Brunker - 5 months ago 52
Python Question

Read/write kivy widget attributes with python

I have a basic, working knowledge of Python I'm trying to teach myself kivy. I'd like to be able to have Python read and write data to kivy widgets.

Imagine there's an address book app that inserts the date and time into a TextInput. When the app starts, just have Python get the date and time and insert it right?

This program code will give an example of a simple address book:

from kivy.app import App

from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput

class AddressApp(App):
def build(self):
pass

if __name__ == '__main__':
AddressApp().run()


Here's its address.kv file:

GridLayout:
cols: 2
Label:
text: 'Date'
TextInput:
id: textinputdate
Label:
text: 'Time'
TextInput:
id: textinputtime
Label:
text: 'Name'
TextInput:
id: textinputname
Label:
text: 'Address'
TextInput:
id: textinputaddress
Label:
text: 'email'
TextInput:
id: textinputemail
Label:
text: 'Phone'
TextInput:
id: textinputphone


After that, if I wanted to have Python read the... I dunno... uh... phone number TextInput, how would that be done?

Answer

A guy named spinningD20 on the FreeNode IRC channel for kivy showed me this.

There's an even easier way than adding a custom widget. As long as you just want to insert a value into the TextInput when the app starts up...

address.py

from kivy.app import App

from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput

import time

class AddressApp(App):
        def build(self):
            self.root.ids.textinputdate.text = time.strftime("%x")

if __name__ == '__main__':
        AddressApp().run()

address.kv

GridLayout:
    cols: 2
    Label:
        text: 'Date'
    TextInput:
        id: textinputdate
    Label:
        text: 'Time'
    TextInput:
        id: textinputtime
    Label:
        text: 'Name'
    TextInput:
        id: textinputname
    Label:
        text: 'Address'
    TextInput:
        id: textinputaddress
    Label:
        text: 'email'
    TextInput:
        id: textinputemail
    Label:
        text: 'Phone'
    TextInput:
        id: textinputphone