【问题标题】:kivy Error when trying to add a button on gridlayot in a different class尝试在不同类的gridlayot上添加按钮时出现kivy错误
【发布时间】:2018-11-13 21:11:23
【问题描述】:

我的应用想要从TextInput 字段中键入的字符串创建一个列表,并在按下按钮"Buscar" 后将它们显示在窗口中间的gridlayout 中。我在类之间共享变量和函数,但是当我尝试在gridlayout 内添加一个带有TextInput.text 的新按钮时会显示错误消息:

"AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'add_widget'" 

谢谢

The interface looks like this

这是我的 .py 文件

from kivy.app import App
from kivy.uix.button import Button
from kivy.properties import ObjectProperty, NumericProperty, StringProperty
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scrollview import ScrollView

class Lista(ScrollView):
    lista_repuestos = ObjectProperty()

class CustomWidget(FloatLayout):
    campo_de_busqueda_text_input = ObjectProperty()
    repuesto = StringProperty('')

    def submit_repuesto(self):
        self.repuesto = self.campo_de_busqueda_text_input.text
        Lista.lista_repuestos.add_widget(Button(text=self.repuesto))


class CustomWidgetApp(App):
    def build(self):
        return CustomWidget()

if __name__ == "__main__":
    CustomWidgetApp().run()

这是我的 .kv 文件

CustomWidget:

<CustomWidget>:

    campo_de_busqueda_text_input: campodebusqueda

    TextInput:
        id: campodebusqueda
        size_hint: .7, .1
        pos_hint: {"x": .15, "y": .85}

    Button:
        on_release: root.submit_repuesto()
        size_hint: .1, .1
        pos_hint: {"x": .85, "y": .85}
        text: "Buscar"

    Label:
        size_hint: .15, .05
        pos_hint: {"x": .05, "y": .15}
        text: "Descripción"
        text_size: self.size
        halign: "left"
    Label:
        size_hint: .15, .05
        pos_hint: {"x": .05, "y": .10}
        text: "Referencia"
        text_size: self.size
        halign: "left"
    Label:
        size_hint: .15, .05
        pos_hint: {"x": .05, "y": .05}
        text: "Cantidad"
        text_size: self.size
        halign: "left"


<Lista>:

    lista_repuestos: listarepuestos

    GridLayout:

        id: listarepuestos
        size_hint: .7, .6
        pos_hint: {"x": .15, "y": .25}
        cols: 1
        row_default_height: 50
        row_force_default: True
        padding: 5
        height: self.minimum_height
        size_hint_y: None

【问题讨论】:

    标签: python class layout kivy scrollview


    【解决方案1】:

    您在CustomWidget中的行:

    Lista.lista_repuestos.add_widget(Button(text=self.repuesto))
    

    应该引用Lista 的实例,而不是类本身。

    【讨论】:

    • 嗨 John,Lista 是类,lista_repuestos 是实例,我错了吗?
    • Lista 是类。而lista_repuestos 是ObjectProperty,它将是Lista 实例中的GridLayout。但在创建Lista 的实例之前,它不会引用GridLayout。我在您的 Python 代码或“kv”文件中看不到任何创建Lista 实例的地方。
    • 另外,kv 文件中的CustomWidget: 行没有任何作用,因为您在应用程序的build 方法中创建了CustomWidget。
    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2013-10-18
    相关资源
    最近更新 更多