You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Kivy中GridLayout布局内被按下按钮的坐标

Kivy GridLayout按钮点击获取网格坐标实现方案

核心注意点提前说明

  • 你原有代码存在三个基础问题:
    • 循环创建Button后没有调用self.layout.add_widget(b),按钮不会被添加到布局中
    • Kivy控件的background_color参数取值范围是0~1,传入25会被识别为最大值1,实际显示为纯白色,如果需要深灰色要把RGB值除以255
    • on_press绑定的回调会自动传入触发事件的按钮实例作为参数,原有回调的参数列表缺少该参数,运行会报错
  • Kivy的GridLayout默认填充顺序为:按设置的cols值从左到右排满一行后,自动换到下一行继续排列,第一个添加的控件位于布局左上角位置。

推荐实现方案(创建时绑定坐标,稳定性最高)

创建按钮时直接计算对应坐标,绑定到按钮的自定义属性上,回调时直接读取即可,不会受后续布局子控件变动影响。
修改后的完整代码:

n = int(input())

def call_back(self, press_btn):
    # 直接读取按钮提前绑定的坐标属性
    coord = press_btn.grid_pos
    print(f"按下按钮的网格坐标为:{coord}")
    return coord

self.layout = GridLayout(cols=n, rows=n, 
                         size_hint = (0.5625, 1), 
                         pos_hint={'center_x': 0.5, 'center_y': 0.5})

for i in range(n ** 2):
    # 以左上角为坐标原点计算行列,原点坐标为(0,0)
    row = i // n
    col = i % n
    # 如果需要以左下角为坐标原点,替换row的计算逻辑为:
    # row = (n - 1) - (i // n)
    b = Button(
        on_press=self.call_back,
        # 修正颜色值为0-1区间,这里对应深灰色
        background_color=(25/255, 25/255, 25/255, 1)
    )
    # 给按钮绑定自定义坐标属性
    b.grid_pos = (row, col)
    # 将按钮添加到布局中
    self.layout.add_widget(b)

return self.layout

轻量实现方案(动态反查索引,无需提前存属性)

如果布局内的按钮不会动态增删,也可以在回调触发时,通过按钮在父布局子控件列表的位置反算坐标,不需要提前给按钮绑定属性。
注意:Kivy的children列表是子控件添加顺序的逆序(最后添加的控件在列表首位),计算时需要转换索引。
仅需修改回调函数即可:

def call_back(self, press_btn):
    parent_layout = press_btn.parent
    total_cols = parent_layout.cols
    # 转换逆序索引为实际添加顺序的索引
    real_index = len(parent_layout.children) - 1 - parent_layout.children.index(press_btn)
    # 左上角为原点的坐标计算
    row = real_index // total_cols
    col = real_index % total_cols
    coord = (row, col)
    print(f"按下按钮的网格坐标为:{coord}")
    return coord

内容的提问来源于stack exchange,提问作者Daniil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 20:03:25