【问题标题】:How to work with more than 1 buttons in kivy GridLayout? [ closed ]如何在 kivy GridLayout 中使用超过 1 个按钮? [关闭]
【发布时间】:2021-01-15 17:04:38
【问题描述】:

我正在学习 kivy 布局:网格布局,我在 .kv 文件中创建了几个按钮

<Grid_Layout>:

    GridLayout:
        size: root.width, root.height
        rows: 3
        cols: 3

        Button:
            text: "Top Left"
            on_touch_up: print("HI")

        Button:
            text: "Top Center"

        Button:
            text: "Top Right"

        Button:
            text: "Center Left"

        Button:
            text: "Center Center"

        Button:
            text: "Center Right"

        Button:
            text: "Bottom Left"

        Button:
            text: "Bottom Center"

        Button:
            text: "Bottom Right"

想问:

  • 如果不加size: root.width, root.height整个布局会一起收缩,有什么解决办法吗?
  • 就像按下一个特定的按钮一样,它会做一些事情,但它们并不相同。我试过on_touch_up: print("HI"),但无论我按下哪个按钮,它都会打印“HI”,哈哈,但我不想要这个:(所以想问有没有解决方案?:)

谢谢 :)

【问题讨论】:

    标签: python button kivy


    【解决方案1】:

    您没有显示Grid_Layout 类的定义,这可能是您的布局改变大小的关键。

    要使用Button,您应该定义on_presson_release 而不是on_touch_up,如下所示:

        Button:
            text: "Top Left"
            on_release: print("HI")
    

    如果您的Grid_Layout 类定义为:

    class Grid_Layout(GridLayout):
        pass
    

    那么您的Grid_Layout 类是GridLayout,因此您无需在其中添加另一个GridLayout。这实际上是在GridLayout 中创建GridLayout,如果这是您想要的,那是可以的,但在您发布的代码中不是必需的。你的kv 可以是这样的:

    <Grid_Layout>:
        rows: 3
        cols: 3
    
        Button:
            text: "Top Left"
            on_release: print("HI")
    
        Button:
            text: "Top Center"
    .
    .
    .
    

    还有

    size: root.width, root.height
    

    不需要。

    【讨论】:

    • 好像我必须在 .py 文件中添加 def Grid_Layout(GridLayout): pass
    • 哦,我刚刚在 .py 文件中添加了 class Grid_Layout(GridLayout): pass 并在 .kv 文件中取消了 GridLayout: 并且它有效:) ?? 哈哈,感谢您的帮助
    • oic ~ 我明白了:)
    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多