Forum Archive

Basic Doubt With Linking Segmented Control

ramvee

Hi,
I am struggling with a very silly doubt whole afternoon. I am making a beginner's mistake, as I am not able to update the text field with choice made by segmented control. Please help!
Thank you!

# Just To Update The TextField With Choice
# Made In Segmented control
# coding: utf-8


import ui


def segment_action(sender):
    if control.selected_index == 0:
        sender.superview['text_field'].text = 'Hello'
    elif control.selected_index == 1:
        sender.superview['text_field'].text ='World'

view = ui.View()
view.name = 'Segment'
view.frame = (0,0,360,600)
view.bg_color='white'

text_field = ui.TextField()
text_field.frame = (130,200,100,50)
text_field.text = 'Namaste'
text_field.alignment = 1
view.add_subview(text_field)

control = ui.SegmentedControl()
control.frame =(130,50,100,50)
control.segments = ('Hello' , 'World')

control.action = segment_action

view.add_subview(control)

view.present('sheet')
omz

You need to set the text field's name attribute in order to access it like you do in the segment_action function.

Simply add text_field.name = 'text_field' after your text field initialization code, and it should work.

ramvee

Thank You @omz ,
That works perfectly!
Oh, the time i wasted on that.
BTW, I am a big fan of Pythonista!!
Thank you for giving us such a brilliant program.

ram

ps. I follow you on twitter and recommend to this app to all my friends.

dgelessus

In this case, you can also use text_field directly, because you've put your text field in a variable.

def segment_action(sender):
    if control.selected_index == 0:
        text_field.text = 'Hello'
    elif control.selected_index == 1:
        text_field.text = 'World'

This doesn't work when you create control and text_field in the UI designer and load the views using load_view. Then you need to give everything a name in the UI designer, and access all views through sender:

def segment_action(sender):
    if sender.selected_index == 0:
        sender.superview['text_field'].text = 'Hello'
    elif sender.selected_index == 1:
        sender.superview['text_field'].text = 'World'
ramvee

Thank You For The Helpful Options @dgelessus !
Finally I am getting somewhere.. with UI module in Pythonista!
:))