Search code examples
pythonkivykivy-language

how to print the text inputs from the loop in kivy


i want to print all user text inputs when i press the button. the problem when i press the button to print the inputs appear the error TypeError: p() takes 1 positional argument but 2 were given. just to know the number to text inputs may vary from user to other

from kivy.uix.textinput import TextInput
from kivy.app import App
from kivy.uix.button import Button
from kivy.lang.builder import Builder

kv=Builder.load_string('''
ScrollView:
    GridLayout:
        id:inputs
        cols:1
        row_force_default:True
        row_default_height:30
        size_hint_y:None
        height:self.minimum_height
''')

class Accounting(App):
    def build(self):return kv

    def on_start(self):
        self.return_list = [] #print this list
        w = Button(text='print all the text inputs',on_press=self.p)
        self.return_list.append(w)
        self.root.ids.inputs.add_widget(w)
        for i in range(5):
            w = TextInput()
            self.return_list.append(w)
            self.root.ids.inputs.add_widget(w)
        return self.return_list

    def p(self):print(self.return_list)#here

Accounting().run()

Solution

  • When you click button then Kivy runs it with extra argument p(widget) so you can assign function to many buttons and you will see which button was clicked.

    But it means you have to get this value in function

        def p(self, widget):
    

    Minimal working code.

    If you want text only from TextInput then removed Button from return_list.

    from kivy.uix.textinput import TextInput
    from kivy.app import App
    from kivy.uix.button import Button
    from kivy.lang.builder import Builder
    
    kv = Builder.load_string('''
    ScrollView:
        GridLayout:
            id:inputs
            cols:1
            row_force_default:True
            row_default_height:30
            size_hint_y:None
            height:self.minimum_height
    ''')
    
    class Accounting(App):
        
        def build(self):
            return kv
    
        def on_start(self):
            self.return_list = [] #print this list
            
            w = Button(text='print all the text inputs', on_press=self.p)
            self.return_list.append(w)
            self.root.ids.inputs.add_widget(w)
            
            for i in range(5):
                w = TextInput()
                self.return_list.append(w)
                self.root.ids.inputs.add_widget(w)
    
            return self.return_list
    
        def p(self, widget):
            print('widget:', widget)
            print('text  :', widget.text)
            
            for item in self.return_list:
                print(item.text)
    
    Accounting().run()