from ui import View, TextField, Label
from collections import deque
''' simple conversation bot:
prompt label
[__textfield__________]
'''
#create a 400x400 view to be our container
v=View(frame=(0,0,400,400), bg_color='white')
#create a prompt label
prompt=Label(frame=(0,0,400,44))
#create an empty textfield
tf=TextField(frame=(0,50,400,44))
#add the elements to the view
v.add_subview(prompt)
v.add_subview(tf)
'''the concept here is to create a sequence of callbacks. each callback must respond to the text in the textbox, and take some other action, like updating the propmpt in response, storing variables, then setting up for the next action. '''
#just to allow creations of pactions that we can cycle through
action_queue=deque()
def next_action():
'''load the next action into the textfield'''
tf.action=action_queue.popleft()
action_queue.append(tf.action)
def ask_name(sender):
''' ask the user for his/her name'''
prompt.text='What is your name'
tf.text=''
next_action()
def ask_age(sender):
'''called in response to ask_name prompt, respond with the name and ask age'''
username=tf.text
tf.text=''
prompt.text='Hello, {} how old are you?'.format(username)
#save this for later. a lazy but easy approach is to stash attributes in your ui components.
tf.username=username
next_action()
def comment_on_age(sender):
'''use previously stored name variable'''
try:
age=int(tf.text)
except ValueError:
prompt.text='Huh? Age is a just a number, what is yours?'
tf.text=''
return
tf.text=''
if age < 20:
prompt.text='You whole life is ahead of you, {}'.format(tf.username)
elif age < 40:
prompt.text='These are your best years, enjoy them'
elif age >= 40:
prompt.text='Is it all downhill from here, {}?'.format(tf.username)
next_action()
#now, setup our sequence of actions, then call the first action to start us off.
action_queue.extend([ask_name, ask_age, comment_on_age])
next_action()
tf.action(tf)
v.present('sheet')
This is probably a bad example, since this is more of a dialog than a TextField.