我想在add_category_to_tree()
课程中按SAVE按钮时从TreeCategory
课程调用方法AddCategoryPopup
。但是,我有问题如何引用在KV文件中创建的TreeCategory实例。
我试图搜索解决方案,但没有任何作用。目前我收到AttributeError: 'super' object has no attribute '__getattr__'
错误。
我该如何正确地做到这一点?谢谢你的帮助
class TreeCategory(TreeView):
def __init__(self, **kwargs):
super(TreeCategory, self).__init__(**kwargs)
def add_category_to_tree(self, name):
self.add_node(TreeViewLabel(text = name.upper()))
class AddCategoryPopup(Popup):
def save(self):
self.ids.tree.add_category_to_tree(self.ids.entry.text) # ????
db.adding_to_db('kategorie', 'nazwa', self.ids.entry.text)
self.dismiss()
def close(self):
self.dismiss()
class MainScreen(BoxLayout):
tree = ObjectProperty(None)
def add_category_button(self):
popup = AddCategoryPopup(title = 'Dodawanie nowej kategorii')
return popup.open()
class GuiCookBookApp(App):
def build(self):
self.title = "Książka kucharska"
return MainScreen()
if __name__ == "__main__":
db = DatabaseManager("cookbook.sqlite")
GuiCookBookApp().run()
KV档案:
<AddCategoryPopup>:
BoxLayout:
orientation: 'vertical'
TextInput:
id: entry
multiline: False
hint_text: 'Podaj nazwę kategorii...'
BoxLayout:
orientation: 'horizontal'
Button:
text: 'SAVE'
on_press: root.save()
Button:
text: 'CANCEL'
on_press: root.close()
<MainScreen>:
orientation: "vertical"
display: entry
tree: tree
BoxLayout:
id: menu
size_hint_y: .1
Button:
text: 'Dodaj kategorię'
on_press: root.add_category_button()
BoxLayout:
id: recipe_view
orientation: "horizontal"
TreeCategory:
id: tree
hide_root: True
size_hint: .25, 1
答案 0 :(得分:0)
你可以通过多种方式做到这一点。例如,您可以将.kv放在主.py文件中。
w = Builder.load_string('''
Widget:
height: self.width / 2. if self.disabled else self.width
x: self.y + 50
''')
https://kivy.org/docs/api-kivy.lang.builder.html
您只需命名.kv文件
即可guicookbookapp.kv
并将其保留在项目的根目录中。
https://kivy.org/docs/examples/gen__application__app_with_kv__py.html
您还可以添加以下内容
from kivy.lang import Builder
Builder.load_file('guicookbookapp.kv')
希望我能正确理解你的问题。
答案 1 :(得分:0)
使用Python中的self.ids
,您只能从该特定类访问KV中的ID。所以self.ids.tree
只能在Python的MainScreen
类中,而不能在AddCategoryPopup
类中。
您可以创建一个ObjectProperty
&#39; topwidget&#39;在AddCategoryPopup
规则中,在实例化弹出窗口时传入Main类。类似的东西:
popup = AddCategoryPopup(topwidget=self)
然后在&#39; save&#39;自定义弹出类的方法,您可以执行以下操作:
self.topwidget.tree...