[英]Referencing Buttons Created Dynamically to a Corresponding Lable Kivy Python
[英]Referencing id of dynamically created widget in Kivy
我無法通過綁定到button的方法中的root.ids.created_in_kv.created_in_py訪問動態創建的子級 。 當我檢查root.ids.created_in_kv.ids字典時,它為空,但是root.ids.created_in_kv.children中有子級
我要實現的目標是創建一個充當多選器的彈出窗口。 它將接受可能的選擇,並動態創建標簽-復選框對並將其添加到彈出內容,並且在“應用”按鈕上,它將僅返回選擇的列表(str())。
我無法在kv中構造帶有多個小部件的彈出窗口,但是以下工作方式(建議使其“更精細”,而不是受歡迎):
驗證碼:
<SelectorPopup>:
title: 'empty'
BoxLayout:
id: inside
orientation: 'vertical'
BoxLayout:
id: options
BoxLayout:
id: buttons
orientation: 'vertical'
Button:
text: 'Apply'
on_release: root.return_selected()
Button:
text: 'Cancel'
on_release: root.dismiss()
<LabeledCheckbox@BoxLayout>:
id: entity
CheckBox:
id: choice
Label:
text: root.id
我正在創建python-checkbox對(打包在GridLayout中)的python代碼,並將其放入選項BoxLayout中 :
class SelectorPopup(Popup):
def return_selected(self):
selected=[]
a = self.ids.inside.options.choices.ids # dict is empty
for item in a.keys():
selected.append(item) if a[item].ids.choice.value #add if checkbox checked
return selected
class MultiselectForm(BoxLayout):
data = ListProperty([])
def __init__(self, **kwargs):
super(MultiselectForm, self).__init__(**kwargs)
self.prompt = SelectorPopup()
def apply_data(self):
# write data to self.data
pass
def create_popup(self):
try:
# some code to check if choices are already created
check = self.prompt.ids.inside.options.choices.id
except AttributeError:
possible = ['choice1','choice2','choice3'] #query db for possible instances
choices = GridLayout(id='choices',cols=2)
for entity in possible:
choice = Factory.LabeledCheckbox(id=entity)
choices.add_widget(choice)
self.prompt.ids.options.add_widget(choices)
self.prompt.open()
問題:
1)如何使return_selected方法起作用?
2)有沒有一種方法可以更好地構造彈出窗口? 我無法將小部件樹添加到內容 ObjectProperty中,例如:
<MyPopup>:
content:
BoxLayout:
Label:
text: 'aaa'
Label:
text: 'bbb'
您似乎對ID的工作方式有些困惑。 在文檔中對它們進行了一些討論: https : //kivy.org/docs/api-kivy.lang.html
基本上,它們只是.kv
中的特殊標記,可讓您引用已定義的小部件。 收集它們並將它們放在定義它們的規則的根窗口小部件的ids
字典中。這意味着它們不像您引用它們時那樣嵌套,它們都在根窗口小部件( SelectorPopup
或LabeledCheckbox
)上
因此,而不是(從SelectorPopup
內部):
self.ids.inside.options.choices
你將會擁有:
self.ids.choices
這也意味着動態添加的小部件將不會出現在ids
字典中,但實際上並不需要。 由於您是用代碼創建它們的,因此您可以自己保存對它們的引用(使用.kv
很難做到)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.