首页 > 解决方案 > 从 .kv 类获取值到 .py 函数

问题描述

我在 main.kv 文件中有自定义类,通过命令我可以添加到 createRecipe.kv 文件中的另一个屏幕。但是如何将 names.text(来自标签)、unit.text(来自标签)和 qtyRe.text(来自 TextInput)读取到 main.py 文件?

screen_manager.get_screen('createRecipe').ingredientforRecipe.add_widget(AddIngToRecipe(names=names, unit=unit))

主文件

<AddIngToRecipe>
    id: addIngToRecipe
    names: names    
    unit: unit
    MDLabel:
        id: names
        text: str(root.names)
        markup: True
        font_size: '20sp'
        size_hint_x: .8
        pos_hint: {"center_x": .4, "center_y": .4}
    MDLabel:
        id: unit
        text: str(root.unit)
        markup: True
        font_size: '18sp'
        size_hint_x: .8
        theme_text_color: "Custom"
        text_color: 1, 1, 1, 1
        pos_hint: {"center_x": .73, "center_y": .4}
    TextInput:
        id: qtyRe
        hint_text: 'Qty:'
        size_hint: 1, None
        input_filter: 'int'
        pos_hint: {"center_x": .5, "center_y": .5}
        height: 55
        cursor_color: 75/255, 0/255, 130/255, 1
        background_color: 0, 0, 0, 0
        multiline: False

创建食谱.kv

MDScreen:
    name: 'createRecipe'
    ingredientforRecipe: ingredientforRecipe

    MDFloatLayout:
        id: create_recipe

        ScrollView:
        do_scroll_y: True
        do_scroll_x: False
        size_hint_y: .41
        pos_hint: {"center_x": .55, "y": 0.41}
        bar_width: 0
        GridLayout:

            id: ingredientforRecipe
            cols: 1
            height: self.minimum_height
            row_default_height: 70
            size_hint_y: None

主文件

class AddIngToRecipe(FakeRectangularElevationBehavior, FloatLayout, TouchBehavior):
    names = ObjectProperty()
    unit = ObjectProperty()
    def get_from(self):
        names1 = self.ids.qtyRe.text
        print(names1)

class PieceofCake(MDApp, Screen):
    def create_recipe(self, Renames, Recomment):
        self.get_from_addIngToRecipe = AddIngToRecipe()
        self.get_from_addIngToRecipe.get_from()
        names = self.ids.ingredientforRecipe.qtyRe.text
        print(names)
        print(Renames)
        print(Recomment)

标签: pythonkivy

解决方案


names = self.ids.names.text
unit = self.ids.unit.text
qtyRe = self.ids.qtyRe.text

此外,如果您想从与您正在使用的类不同的类中访问小部件的值,您可以使用:

MDApp.get_running_app().root.ids.idOfTheClass.ids.idOfTheWidget.valueToGet

MDApp.get_running_app().root.ids.idOfTheClass作用与self目标类相同


推荐阅读