如何在Kivy应用程序运行时添加小部件



我声明我不是Python专家,我最近才开始使用Kivy!我想知道在应用程序运行时添加按钮或标签等小部件是否可能,是否有意义。例如,每次按下按钮都会在屏幕上添加一个新按钮。我不知道我是否已经足够清楚了。

此示例通过创建新的Button来说明该过程。每次按下另一个Button时,您还可以删除(移除(创建的按钮。

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

class CustomBox(BoxLayout):
def add_buttons(self, *args):
"""Method for creating new Button."""
i = len(self.ids.inner_box.children) # Just to distinguish the buttons from one another.
btn = Button(
text = f"Button {i+1}",
size_hint_y = None,
height = "64dp",
)
self.ids.inner_box.add_widget(btn) # Referencing container by its 'id'.

Builder.load_string("""
<CustomBox>:
orientation: "vertical"
spacing: dp(2)
Button:
size_hint_y: 0.5
text: "Add Button"
color: 0, 1, 0, 1
on_release: root.add_buttons()
ScrollView: # To see and add all the buttons in progress.
BoxLayout: # Button's container.
id: inner_box
orientation: "vertical"
spacing: dp(5)
padding: dp(5)
size_hint_y: None # Grow vertically.
height: self.minimum_height # Take as much height as needed.
Button:
size_hint_y: 0.5
text: "Delete Button"
color: 1, 0, 0, 1
on_release: inner_box.remove_widget(inner_box.children[0]) if inner_box.children else None # Here '0' means last added widget.
""")

class MainApp(App):
def build(self):
return CustomBox()

if __name__ == '__main__':
MainApp().run()
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class BeginnerApp(App):

def build(self):
root = BoxLayout(orientation='vertical')
self.count = 0

a = root.add_widget(Button(text='add button', on_press=self.add_button))

b = root.add_widget(Button(text='remove button', on_press=self.delete_button))

return root


def add_button(self, *args):
self.count += 1
self.root.add_widget(Button(text=str(self.count)))

def delete_button(self, *args):
if self.count > 0:
self.root.remove_widget(self.root.children[0])
self.count -= 1
else:
pass


if __name__ == '__main__':
app = BeginnerApp()
app.run()

注意1:绑定方法时,请指定不带括号的名称。否则,绑定将无法正常工作。

on_press=self.add_button
on_press=self.delete_button

注2:要在布局中添加小部件,您可以使用方法"add_widget((";。

self.root.add_widget(Button())

对于删除小部件,您可以使用方法";remove_widget(("。要删除布局中的小部件,您需要指定此小部件。这可以通过";儿童";方法";儿童";方法被编号为";0〃;。因此,您可以删除布局中的最后一个小部件。

self.root.remove_widget(self.root.children[0])

注意3:在声明方法时,不要忘记*args。

def add_button(self, *args):

最新更新