【问题标题】:How do you position a MDChip through code?如何通过代码定位 MDChip?
【发布时间】:2022-01-08 11:48:14
【问题描述】:

我正在开发一个应用程序,但不知道如何定位 MDChip。基本上我想在 MDCard 上添加一个新的 MDChip。我希望将 MDChips 定位在中心,并且对于添加的每个新芯片,然后向下放置。这是我的python文件:

from kivymd.app import MDApp
from kivymd.uix.chip import MDChip
from kivy.lang import Builder

class App(MDApp):

    Current_Item = 0
    Chips = []

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.screen = Builder.load_file("main.kv")

    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Blue"
        return self.screen

    def add_item(self):
        self.Chips.append(MDChip(text = self.root.ids.text_field_1.text, icon = "close-circle-outline", on_press = self.remove_item, pos_hint = {"center_x": 100, "center_y": 0.95}))
        self.root.ids.card_1.add_widget(self.Chips[self.Current_Item])
        self.Current_Item += 1
        self.root.ids.text_field_1.text = ""

    def remove_item(self, obj):
        self.Current_Item -= 1
        self.root.ids.card_1.remove_widget(self.Chips[self.Current_Item])
        self.Chips.pop()

App().run() 

我的kv文件:

MDScreen:
    MDTextField:
        id: text_field_1
        pos_hint: {"center_x": 0.5, "center_y": 0.95}
        size_hint_x: 0.5
        
    MDIconButton:
        icon: "plus-circle"
        id: button_enter
        pos_hint: {"center_x": 0.82, "center_y": 0.95}
        on_press: app.add_item()

    MDCard:
        id: card_1 
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        size_hint_x: 0.5
        size_hint_y: 0.8

【问题讨论】:

  • MDCardBoxLayout 类的子类。因此,您可以将其属性orientation 设置为“垂直”,以将其子项从下到上垂直放置。如果你想把它们放在中间,你可能更喜欢FloatLayout 甚至StackLayout。但是,MDChippos_hintcenter_x 值不应该介于 0 和 1 之间。

标签: python python-3.x kivy kivymd


【解决方案1】:

感谢@ApuCoder,我通过向 MDCard 添加 StackLayout 找到了有效答案。

MDCard:
        id: card_1
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        size_hint_x: 0.5
        size_hint_y: 0.8
        orientation: "vertical"

        StackLayout:
            id: stack_layout_1
            pos_hint: {"center_x": 0.5}
            size_hint_x: 0.1
            spacing: 5

这改变了这一行:

self.Chips.append(MDChip(text = self.root.ids.text_field_1.text, icon = "close-circle-outline", on_press = self.remove_item, pos_hint = {"center_x": 0.5}))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2023-03-13
    相关资源
    最近更新 更多