user3603948
user3603948

Reputation: 153

Kivy get TextInput from Popup

I have a simple app that asks for your name and age in a TextInput field. When you click the save button a Popup opens and you can save the name and age from the TextInput in a file.

Question: How can I access the Name and Age when the Popup is already open? Right now I store the TextInput data in a dictionary before I open the Popup. This workaround does work, but there most certainly is a more elegant solution than this:

class SaveDialog(Popup):
    def redirect(self, path, filename):
        RootWidget().saveJson(path, filename)
    def cancel(self):
        self.dismiss()

class RootWidget(Widget):
    data = {}

    def show_save(self):
        self.data['name'] = self.ids.text_name.text
        self.data['age'] = self.ids.text_age.text
        SaveDialog().open()

    def saveFile(self, path, filename):
        with open(path + '/' + filename, 'w') as f:
            json.dump(self.data, f)
        SaveDialog().cancel()

Upvotes: 1

Views: 5568

Answers (1)

el3ien
el3ien

Reputation: 5405

Yoy can pass your object to the popup object. That way you can accsess all the widgets attributes for the popup object. An example of this can look like this.

from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.app import App


class MyWidget(BoxLayout):

    def __init__(self,**kwargs):
        super(MyWidget,self).__init__(**kwargs)

        self.orientation = "vertical"

        self.name_input = TextInput(text='name')

        self.add_widget(self.name_input)

        self.save_button = Button(text="Save")
        self.save_button.bind(on_press=self.save)

        self.save_popup = SaveDialog(self) # initiation of the popup, and self gets passed

        self.add_widget(self.save_button)


    def save(self,*args):
        self.save_popup.open()


class SaveDialog(Popup):

    def __init__(self,my_widget,**kwargs):  # my_widget is now the object where popup was called from.
        super(SaveDialog,self).__init__(**kwargs)

        self.my_widget = my_widget

        self.content = BoxLayout(orientation="horizontal")

        self.save_button = Button(text='Save')
        self.save_button.bind(on_press=self.save)

        self.cancel_button = Button(text='Cancel')
        self.cancel_button.bind(on_press=self.cancel)

        self.content.add_widget(self.save_button)
        self.content.add_widget(self.cancel_button)

    def save(self,*args):
        print "save %s" % self.my_widget.name_input.text # and you can access all of its attributes
        #do some save stuff
        self.dismiss()

    def cancel(self,*args):
        print "cancel"
        self.dismiss()


class MyApp(App):

    def build(self):
        return MyWidget()

MyApp().run()

Upvotes: 3

Related Questions