且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python:如何动态添加行

更新时间:2023-12-06 11:06:46

您可以为RowRows创建自定义类,然后使用添加行的方法.
我对您的示例做了一些修改.试试这个:

You can make a custom class for Row and Rows, then have a method adding rows.
I modified your example a bit. Try this:

from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty

Window.size = (450, 525)


class display(Screen):

    def add_more(self):
        self.ids.rows.add_row()


class Row(BoxLayout):
    button_text = StringProperty("")


class Rows(BoxLayout):
    orientation = "vertical"
    row_count = 0

    def __init__(self, **kwargs):
        super(Rows, self).__init__(**kwargs)
        self.add_row()

    def add_row(self):
        self.row_count += 1
        self.add_widget(Row(button_text=str(self.row_count)))


class test(App):

    def build(self):
        self.root = Builder.load_string(KV)
        return self.root



KV = """

<Row>:
    orientation: "horizontal"
    spacing: 0, 5

    Button:
        text: root.button_text
        size_hint_x: .2

    TextInput:
        size_hint_x: .8


display:

    BoxLayout:
        orientation: "vertical"
        padding : 20, 20

        BoxLayout:
            orientation: "horizontal"

            Button:
                size_hint_x: .2
                text: "+Add More"
                valign: 'bottom'
                on_press: root.add_more()


        BoxLayout:
            orientation: "horizontal"

            Label:
                size_hint_x: .2
                text: "SN"
                valign: 'bottom'

            Label:
                size_hint_x: .8
                text: "Value"
                valign: 'bottom'


        Rows:
            id: rows

        BoxLayout:
            orientation: "horizontal"
            padding : 10, 0
            spacing: 10, 10
            size_hint: .5, .7
            pos_hint: {'x': .25, 'y':.25}

            Button:
                text: 'Ok'
                on_release:
                    root.dismiss()

            Button:
                text: 'Cancel'
                on_release: root.dismiss()

"""


test().run()