Forum Archive

Button + Textfield Saving to Variable

techteej

I'm just starting to use the ui module. How would I connect a button to a textfield to save the text to a variable? This is what I have so far.

# coding: utf-8

import ui

v = ui.load_view('Untitled 2')
textfield = v['textfield1']
button1 = v['button1']
v.present('sheet')
omz

You need to assign an action to your button. This is basically just a function that gets called automatically when your button is tapped. Example, based on your code:

# coding: utf-8

import ui

v = ui.load_view('Untitled 2')
textfield = v['textfield1']

def button_action(sender):
    text = textfield.text
    print text

button1 = v['button1']
button1.action = button_action
v.present('sheet')

You can also set the action directly in the UI editor instead of assigning it in code (you would just enter "button_action" there, but you need to make sure that the function is defined before you load the view).

techteej

Ok thank you. How do I dismiss this without user having the tap the x? Is that possible?

omz

Calling ui.close_all() is the easiest way.

techteej

Thanks again!