добавление двух или более значений в кивы и получение результата динамического массива c - PullRequest
0 голосов
/ 08 февраля 2020

Я новичок в Киви, и мне нужна ваша помощь .. У меня есть маленький вопрос:

Мне нужен массив динамических c, который пользователь может ввести первое значение в самом начале TextInput Box он может нажать кнопку «новая строка» , он получает возможность ввести второе значение в новое поле TextInput, чем он может снова нажмите кнопку «новая строка» .. у него есть возможность ввести третье значение в новое поле TextInput .. в любое время он может нажать «Result» .., чтобы получить сумму этих значений в метке

Как я могу сделать этот динамический c массив ? Спасибо

Ответы [ 3 ]

0 голосов
/ 08 февраля 2020

Хорошо, в вашем случае это будет выглядеть так:

.py файл:

# import this
from kivy.properties import ObjectProperty
from kivy.clock import Clock
...
class MainWindow(Screen):

    def __init__(self, **kwargs):
        super(MainWindow, self).__init__(**kwargs)
        # we have to delay running that function, it will run when kv file will be ready to provide widgets by id
        Clock.schedule_once(self.getids)
        self.counter = 1
        self.textlist = [TextInput()]
        self.grid.add_widget(Label(text='Input value ' + counter))
        self.counter += 1
        self.grid.add_widget(self.textlist[0])

    # don't forget this
    grid = ObjectProperty(None)

    # function to connect layout with the variable
    def getids(self):
        self.grid = self.ids.grid

# function to create new inputs, that button 'new line' calls:
    def addnewtextinput(self):
        self.grid.add_widget(Label(text='Input value ' + self.counter))
        self.counter += 1
        self.textlist.append(TextInput())
        self.grid.add_widget(self.textlist[-1])

# function to get a result:
    def getresult(self):
        result = 0
        for i in self.textlist:
        # you may convert it to float if you need, like float(i.text)
            result += int(i.text)
        self.ids.label_id.text = str(result)

class MyMainApp(App):
        def build(self):
            self.b1 = WindowManager()
            self.b1.add_widget(MainWindow())
            return self.b1

.kv файл:

<MainWindow>:
    name: "main"
    # don't forget to add this
    grid: grid.__self__

    GridLayout:
        cols:1

        # you will control that GridLayout from .py so here it's empty
        GridLayout:
            # set the id to be able to control it from .py file
            id: grid
            cols: 2

        CustButton:
            text: "new line"
            on_press: root.addnewtextinput()

        CustButton:
            text: "result"
            font_size: "30sp"
            on_press: root.getresult()

        TextInput:
            id:label_id
            font_size: 40
            multiline: True 
0 голосов
/ 08 февраля 2020

H Lothri c .. это код main.py

    from kivy.uix.textinput import TextInput
    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen


    class MainWindow(Screen):

        def __init__(self, **kwargs):
            super(MainWindow, self).__init__(**kwargs)
            self.counter = 1
            self.textlist = [TextInput()]
            self.ids.grid.add_widget(Label(text='Input value ' + self.counter))
            self.counter += 1
            self.ids.grid.add_widget(self.textlist[0])

    # function to create new inputs, that button 'new line' calls:
        def addnewtextinput(self):
            self.ids.grid.add_widget(Label(text='Input value ' + self.counter))
            self.counter += 1
            self.textlist.append(TextInput())
            self.ids.grid.add_widget(self.textlist[-1])

    # function to get a result:
        def getresult(self):
            result = 0
            for i in self.textlist:
            # you may convert it to float if you need, like float(i.text)
                result += int(i.text)
            self.ids.label_id.text = str(result)


    class WindowManager(ScreenManager):
    pass


    class MyMainApp(App):
        def build(self):
            b1=WindowManager()
            MainWindow()
            return b1


    if __name__ == "__main__":
        MyMainApp().run()

и это main.kv

<CustButton@Button>:
    font_size: 40

WindowManager:
    MainWindow:

<MainWindow>:
    name: "main"

    GridLayout:
        cols:1

        # you will control that GridLayout from .py so here it's empty
        GridLayout:
            # set the id to be able to control it from .py file
            id: grid
            cols: 2

        CustButton:
            text: "new line"
            on_press: root.addnewtextinput()

        CustButton:
            text: "result"
            font_size: "30sp"
            on_press: root.getresult()

        TextInput:
            id:label_id
            font_size: 40
            multiline: True

это код

0 голосов
/ 08 февраля 2020

В чем проблема? Составьте список TextInputs, а затем возьмите значения из него. Как то так:

# create a list with first text input:
self.textlist = [TextInput()]
# I don't know which layout you are using, for example BoxLayout with box variable. Add TextInput to box:
self.box.add_widget(self.textlist[0])

# function to create new inputs, that button 'new line' calls:
def addnewtextinput(self):
    self.textlist.append(TextInput())
    self.box.add_widget(self.textlist[-1])

# function to get a result:
def getresult(self):
    result = 0
    for i in self.textlist:
        # you may convert it to float if you need, like float(i.text)
        result += int(i.text)
    return result
...