【问题标题】:How to access a child of a widget in Kivy?如何访问 Kivy 中小部件的子级?
【发布时间】:2018-10-05 20:17:39
【问题描述】:

我是使用 Kivy 的新手。我定义了一个带有 Button 子项的 FloatLayout 对象。有没有办法访问 Button on_press 事件和背景图片?

这是我试过的代码:

<Tecla2@FloatLayout>:
    Button:
        size_hint: (0.95,1.05)
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        text: ""

Tecla2:
    self.Button.background_normal: "images/tecla_normal1.png"
    self.Button.background_down: "images/tecla_down1.png"
    self.Button.on_press: if(len(texto.text)<text_len): texto.text+="1"

另一种解决方案(我目前实现的)是定义一个 Button 并为每个实例使用一个新的 FloatLayout,但它缺乏优雅:

<Tecla@Button>:
    size_hint: (0.95,1.05)
    pos_hint: {"center_x": 0.5, "center_y": 0.5}
    text: ""

FloatLayout:                    
    Tecla:
        background_normal: "images/tecla_normal2.png"
        background_down: "images/tecla_down2.png"
        on_press: if(len(texto.text)<text_len): texto.text+="2"

有没有使用 kivy 语言来做到这一点?这是最简单的例子,但我已经需要在其他情况下做同样的事情。

【问题讨论】:

  • 你想做什么?一个有多个按钮的 FloatLayout 还是多个每个一个按钮的 FloatLayout?
  • 这是一个网格,有许多 FloatLayout,每个都有一个按钮。

标签: python kivy kivy-language


【解决方案1】:

是否可以访问 Button on_press 事件和背景图像?

嗯,你可以使用你创建的按钮的相关属性:

<Tecla2@FloatLayout>:
    Button:
        size_hint: (0.95,1.05)
        pos_hint: {"center_x": 0.5, "center_y": 0.5}
        text: ""
        background_normal: "images/tecla_normal1.png"
        background_down: "images/tecla_down1.png"
        on_press: if(len(texto.text)<text_len): texto.text+="1"

也许您还在寻找其他东西?

【讨论】:

  • 我可以完成,但是每个实例都有不同的背景和 on_press 事件的不同代码。两者在实例化后仍然需要编辑。
猜你喜欢
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
相关资源
最近更新 更多