Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 782
Dave Brunker Avatar asked Jan 22 '26 19:01

Dave Brunker


1 Answers

If you want some widget to have an extra functionality (example: loading current date at app start), then create a custom version of that widget, which meets requirements. And reading values of widgets within a rule is very simple. Example:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.textinput import TextInput
from kivy.clock import Clock
import time

gui = '''
BoxLayout:
    orientation: 'vertical'

    GridLayout:
        cols: 2

        Label:
            text: 'current time'

        DateInput:
            id: date_input

    Button:
        text: 'write date to console'
        on_press: print(date_input.text)
'''


class DateInput(TextInput):

    def __init__(self, **kwargs):
        super(DateInput, self).__init__(**kwargs)
        Clock.schedule_interval(self.update, 1)  # update every second

    def update(self, dt):
        self.text = time.ctime()


class Test(App):

    def build(self):
        return Builder.load_string(gui)


Test().run()
like image 108
jligeza Avatar answered Jan 24 '26 09:01

jligeza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!