如何使用Kivy添加来自类外的小工具



Hy!我在这里有一个应用程序,有点像;待办事项列表";。当我按下";添加项目";按钮,它打开弹出窗口,我想当";向上";按下按钮以添加";ItemTemplate";在";项目列表";。我是Kivy的新手,最近几天我试着这么做。我该怎么做
非常感谢!

Python代码:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
class FirstBox(BoxLayout):
def btn(self):
Pu().open()
class ItemsList(GridLayout):
pass
class ItemTemplate(BoxLayout):
pass
class Pu(Popup):
pass
class MyAppApp(App):
pass
MyAppApp().run()

Kv代码:

FirstBox:
<FirstBox>:
orientation: "vertical"
BoxLayout:
ScrollView:
ItemsList:
size_hint: 1, None
height: self.minimum_height
Button:
size_hint: 1,0.2
text: "Add Item"
on_release: root.btn()
<ItemsList>:
cols: 1
size_hint_y: None
ItemTemplate:
ItemTemplate:
ItemTemplate:
<ItemTemplate>:
size_hint: 1, None
CheckBox:
size_hint: 0.15, 1
Button:
text: "Task Name"
Button:
text: "Some action"
size_hint: 0.15,1
<Pu>:
size_hint: 1, 0.3
BoxLayout:
orientation: "vertical"
TextInput:
Button:
text: "Up"

为添加小部件的ItemList提供id,为从中获取文本的TextInput提供id。

ItemsList:
id: viewlist

TextInput:
id: new_task_input_id

使用StringProperty定期更改ItemTemplate:的文本

from kivy.properties import StringProperty
class ItemTemplate(BoxLayout):
task_text = StringProperty()

编辑.kv侧第纳尔:(ItemTemplate的按钮)

Button:
text: root.task_text

1kv侧触发向上按钮:on_release: root.add_item()在Pu类中创建此函数并添加以下操作:

def add_item(self,*args):
firstbox = App.get_running_app().root #access correctly main layout
itemlist = firstbox.ids.viewlist #find viewlist by id
new_task_text = self.ids.new_task_input_id.text  #get textinput text
item = ItemTemplate()  #create custom item
item.task_text = new_task_text  #set item text
itemlist.add_widget(item) #add item to layout

短功能:

App.get_running_app().root.ids.viewlist.add_widget(ItemTemplate(task_text=self.ids.new_task_input_id.text))

允许在添加新项目后关闭弹出窗口:

self.dismiss()

另外,如果你想把这个小部件添加到顶部,需要在add_widget:中给出索引

itemlist.add_widget(item,len(itemlist.children))

相关内容

最新更新