Kivy TextInput дан той же переменной - PullRequest
0 голосов
/ 07 марта 2019

Я делаю программу на Python с графическим интерфейсом пользователя (GUI), используя Kivy.Эта программа имеет несколько вкладок, которые содержат 2 TextInput виджетов в сочетании с кнопкой отправки.Чтобы не иметь по одной переменной на TextInput на вкладку (что могло бы создать много переменных), я попытался присвоить все соответствующие TextInput из разных вкладок одной и той же переменной kv, т.е. использовать одни и те же идентификаторы для всех TextInput из разных вкладок,Содержимое переменных kv передается двум переменным Python ObjectProperty.Все типы ввода одинаковы (т. Е. Строка).

При запуске программы и вводе данных на каждой вкладке, один за другим, входы на первой вкладке пусты (при выводе на Python), в то время каквходы второй вкладки работают должным образом.При удалении дублированных идентификаторов со второй вкладки в файле kv lang (т. Е. Повторное создание уникальных идентификаторов TextInput первой вкладки) ввод первой вкладки фиксируется правильно.

Следовательно, повторениеодни и те же идентификаторы в одном и том же файле kv lang приводят к некорректному поведению захвата ввода.

Вот подмножество моего скрипта Python (максимально упрощено, чтобы подвести итог моей проблемы):

class MyLayout(BoxLayout):

    # 2 inputs per tab
    type_text_input = ObjectProperty()  # 1st input
    amount_text_input = ObjectProperty()  # 2nd input
    all_tab_content = [[] for i in range(9)]
    regular_income_type = ObjectProperty()  # combined input

    def synchronizeTabContent(self, i):
        # Give (back) the value corresponding to the current tab to the ListAdapter
        self.regular_income_type.adapter.data = self.all_tab_content[i]

    def submit(self, i):
        # Get user inputs from the TextInputs
        combined_input = self.type_text_input.text + ":" + self.amount_text_input.text
        # Add string to the ListView and to the whole list
        self.regular_income_type.adapter.data.extend([combined_input])
        self.all_tab_content[i] = self.regular_income_type.adapter.data
        # Reset the ListView
        self.regular_income_type._trigger_reset_populate()


class SampleApp(App):
    def build(self):

        # Set the background color for the window
        Window.clearcolor = (0.1, 0.1, 0.1, 1)
        return MyLayout()


if __name__ == "__main__":
    sample_app = SampleApp()
    sample_app.run()

Вот подмножество моего скрипта kv lang:

<SubmitButton@Button>:
    text: "Submit"
    size_hint_x: 15

MyLayout:

<MyLayout>:
    orientation: "vertical"
    type_text_input: type_input  # variable which is empty in first tab
    amount_text_input: amount_input  # variable which is empty in first tab
    regular_income_type: students_list_view
    padding: 10
    spacing: 10

    #### Some layout code was skipped here ####

    BoxLayout:
        orientation: "horizontal"
        height: 30

        BoxLayout:
            orientation: "horizontal"
            size_hint_x: .25
            TabbedPanelItem:
                text: "Regular"
                on_press: root.synchronizeTabContent(4)

                # ----- First tab -----
                BoxLayout:
                    orientation: "vertical"
                    size_hint_x: 1
                    BoxLayout:
                        size_hint_x: 0.95
                        size_hint_y: 0.1
                        height: "40dp"

                        Label:
                            color: (0, 0, 0, 1)
                            text: "Type"
                        TextInput:
                            id: type_input  # here is where is suspect the error comes from
                        Label:
                            color: (0, 0, 0, 1)
                            text: "Amount"
                        TextInput:
                            id: amount_input  # here is where is suspect the error comes from
                    BoxLayout:  # Button box
                        size_hint_y: 0.1
                        height: "40dp"
                        SubmitButton:
                            on_press: root.submit(4)

            # ----- End of first tab -----

            TabbedPanelItem:
                text: "Deposit"
                on_press: root.synchronizeTabContent(5)

                # ----- Second tab -----
                BoxLayout:
                    orientation: "vertical"
                    size_hint_x: 1
                    BoxLayout:
                        size_hint_x: 0.95
                        size_hint_y: 0.1
                        height: "40dp"

                        Label:
                            color: (0, 0, 0, 1)
                            text: "Type"
                        TextInput:
                            id: type_input  # here is where is suspect the error comes from
                        Label:
                            color: (0, 0, 0, 1)
                            text: "Amount"
                        TextInput:
                            id: amount_input  # here is where is suspect the error comes from
                    BoxLayout:
                        size_hint_y: 0.1
                        height: "40dp"
                        SubmitButton:
                            on_press: root.submit(5)

Переменные, которые хранят пустую строку для любого ввода первой вкладки, это self.type_text_input и self.amount_text_input.Соответствующие им kv-переменные type_input и amount_input, которые используются один раз для каждой вкладки и задаются как id TextInput.Я подозреваю, что повторное использование одних и тех же идентификаторов отвечает за мою проблему.

Есть ли способ сохранить входные данные различных TextInput в одной и той же переменной Python, не используя разные переменные kv для каждой * 1028?*

1 Ответ

0 голосов
/ 09 марта 2019

Как предложено @Nearoo, я назначил разные id с каждому TextInput, к которому я обращался из переменной ids в Python, и, таким образом, я смог получить все пользовательские входные данные в одной переменной Python без использования ObjectProperty переменных. Переменная ids - это словарь, ключи которого - это id s, предоставленные в скрипте kv lang, и значениями которых в данном случае являются TextInput.

Окончательный упрощенный код Python:

class MyLayout(BoxLayout):

    # store all tab content
    all_tab_content = [[] for i in range(9)]

    def synchronizeTabContent(self, i):
        # Give (back) the value corresponding to the current tab to the ListAdapter
        self.ids["regular_income{}".format(i)].adapter.data = self.all_tab_content[i]

    def submit(self, i):
        # Get user inputs from the TextInputs
        combined_input = self.ids["type_input{}".format(i)].text + self.sep + self.ids["amount_input{}".format(i)].text
        # Add string to the ListView and to the whole list
        self.ids["regular_income{}".format(i)].adapter.data.extend([combined_input])
        self.all_tab_content[i] = self.ids["regular_income{}".format(i)].adapter.data
        # Reset the ListView
        self.ids["regular_income{}".format(i)]._trigger_reset_populate()


class SampleApp(App):
    def build(self):

        # Set the background color for the window
        Window.clearcolor = (0.1, 0.1, 0.1, 1)
        return MyLayout()


if __name__ == "__main__":
    sample_app = SampleApp()
    sample_app.run()

Последний упрощенный код кванга:

<SubmitButton@Button>:
    text: "Submit"
    size_hint_x: 15

MyLayout:

<MyLayout>:
    orientation: "vertical"
    padding: 10
    spacing: 10

    #### Some layout code was skipped here ####

    BoxLayout:
        orientation: "horizontal"
        height: 30

        BoxLayout:
            orientation: "horizontal"
            size_hint_x: .25
            TabbedPanelItem:
                text: "Regular"
                on_press: root.synchronizeTabContent(4)

                # ----- First tab -----
                BoxLayout:
                    orientation: "vertical"
                    size_hint_x: 1
                    BoxLayout:
                        size_hint_x: 0.95
                        size_hint_y: 0.1
                        height: "40dp"

                        Label:
                            color: (0, 0, 0, 1)
                            text: "Type"
                        TextInput:
                            id: type_input4  # each id is unique
                        Label:
                            color: (0, 0, 0, 1)
                            text: "Amount"
                        TextInput:
                            id: amount_input4  # each id is unique
                    BoxLayout:  # Button box
                        size_hint_y: 0.1
                        height: "40dp"
                        SubmitButton:
                            on_press: root.submit(4)
                                    ListView:
                                        size_hint_y: 0.2
                                        id: regular_income4
                                        adapter:
                                            ListAdapter(data=[], cls=main.StudentListButton)


            # ----- End of first tab -----

            TabbedPanelItem:
                text: "Deposit"
                on_press: root.synchronizeTabContent(5)

                # ----- Second tab -----
                BoxLayout:
                    orientation: "vertical"
                    size_hint_x: 1
                    BoxLayout:
                        size_hint_x: 0.95
                        size_hint_y: 0.1
                        height: "40dp"

                        Label:
                            color: (0, 0, 0, 1)
                            text: "Type"
                        TextInput:
                            id: type_input5  # each id is unique
                        Label:
                            color: (0, 0, 0, 1)
                            text: "Amount"
                        TextInput:
                            id: amount_input5  # each id is unique
                    BoxLayout:
                        size_hint_y: 0.1
                        height: "40dp"
                        SubmitButton:
                            on_press: root.submit(5)
                                    ListView:
                                        size_hint_y: 0.2
                                        id: regular_income5
                                        adapter:
                                            ListAdapter(data=[], cls=main.StudentListButton)

(Обратите внимание, что объекты ListView и ListAdapter были добавлены для целей программы и, следовательно, использовались как ключи ids в synchronizeTabContent и submit методах.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...