如何从用户那里获取输入并将它们保存在列表中(Python Kivy)?

问题描述 投票:0回答:2

我是kivy模块的初学者。我想在屏幕上放置8个文本框以从用户获取输入,然后将此输入保存在列表中以便以后使用它们!

我在互联网上搜索,但没有找到任何有用的东西。

我想我应该像这样的代码:Save text input to a variable in a kivy app

但是不想在shell中显示输入,我想将它们保存在列表中!

python textbox kivy
2个回答
1
投票

Py file

  • 使用for循环遍历所有小部件的容器,例如TextInput

片段

    for child in reversed(self.container.children):
        if isinstance(child, TextInput):
            self.data_list.append(child.text)

kv file

  • 使用容器,例如GridLayout
  • 为容器添加id
  • 将所有这些LabelTextInput小部件添加为GridLayout的子级

片段

    GridLayout:
        id: container
        cols: 2

        Label:
            text: "Last Name:"
        TextInput:
            id: last_name

Example

卖弄.朋友

from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder

Builder.load_file('main.kv')


class MyScreen(Screen):
    container = ObjectProperty(None)
    data_list = ListProperty([])

    def save_data(self):
        for child in reversed(self.container.children):
            if isinstance(child, TextInput):
                self.data_list.append(child.text)

        print(self.data_list)


class TestApp(App):
    def build(self):
        return MyScreen()


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

main.kv

#:kivy 1.11.0

<MyScreen>:
    container: container
    BoxLayout:
        orientation: 'vertical'

        GridLayout:
            id: container
            cols: 2
            row_force_default: True
            row_default_height: 30
            col_force_default: True
            col_default_width: dp(100)

            Label:
                text: "Last Name:"
            TextInput:
                id: last_name

            Label:
                text: "First Name:"
            TextInput:
                id: first_name

            Label:
                text: "Age:"
            TextInput:
                id: age

            Label:
                text: "City:"
            TextInput:
                id: city

            Label:
                text: "Country:"
            TextInput:
                id: country

        Button:
            text: "Save Data"
            size_hint_y: None
            height: '48dp'

            on_release: root.save_data()

Output

Result


1
投票

你需要给你的文本输入ids,然后引用它们的id并使用.text获取它们的文本。 TestApp类中的self.root指的是你的kv文件的根小部件,它是一个没有括号(< >)的文件夹,在本例中是GridLayout

main.py

from kivy.app import App

class MainApp(App):
    def get_text_inputs(self):
        my_list = [self.root.ids.first_input_id.text, self.root.ids.second_input_id.text]
        print(my_list)
    pass

MainApp().run()

main.kv

GridLayout:
    cols: 1
    TextInput:
        id: first_input_id
    TextInput:
        id: second_input_id
    Button:
        text: "Get the inputs"
        on_release:
            app.get_text_inputs()
© www.soinside.com 2019 - 2024. All rights reserved.