Kivy点击按钮获取Canvas内Rectangle位置报错,求技术支持
问题:点击按钮获取KV文件中Rectangle的位置失败
问题场景
点击按钮时尝试从KV文件中获取Rectangle的位置,使用ids实现但报错。
相关代码
game.py
class MainLayout(BoxLayout): def rect_position(self): px, py = self.ids.rect.pos print(px, py)
KV文件
<MainLayout>: orientation: "horizontal" Label: canvas: Rectangle: id: rect pos: (self.width/4 + 50, self.height*3/4) size: (100, 0)
报错信息
position = self.ids.rect.pos File "kivy\properties.pyx", line 864, in kivy.properties.ObservableDict.getattr AttributeError: 'super' object has no attribute 'getattr'
问题原因
Kivy的ids系统仅能识别Widget组件,而canvas下的Rectangle属于图形绘制指令(Canvas Instruction),并非Widget,因此无法通过self.ids.rect直接获取。
解决方法
方案1:绑定位置到Label属性
将Rectangle的位置绑定到Label的自定义属性,通过访问Label的属性间接获取位置:
修改KV文件,给Label添加自定义属性并绑定Rectangle的pos:
<MainLayout>: orientation: "horizontal" Label: id: rect_label # 自定义属性存储Rectangle的位置 rect_pos: (self.width/4 + 50, self.height*3/4) canvas: Rectangle: pos: self.rect_pos size: (100, 0)
对应修改Python代码:
class MainLayout(BoxLayout): def rect_position(self): px, py = self.ids.rect_label.rect_pos print(px, py)
方案2:Python中直接计算位置
如果Rectangle的位置是基于Label尺寸计算的,可直接在Python中通过Label的尺寸参数复用相同公式:
先给Label设置id(同上KV代码),然后修改Python代码:
class MainLayout(BoxLayout): def rect_position(self): label = self.ids.rect_label px = label.width / 4 + 50 py = label.height * 3 / 4 print(px, py)
注意事项
确保Label已完成布局(比如按钮点击触发时),否则width和height可能为初始值0,导致计算出的位置不准确。
内容的提问来源于stack exchange,提问作者Tech123
相关产品推荐
相关产品推荐

