我想在按下按钮时使用python文件从kv文件中获取矩形的位置,任何帮助将不胜感激

问题描述 投票:0回答:1

我尝试使用 ids 但没用,

游戏.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 文件“kivy\properties.pyx”,第 864 行,位于 kivy.properties.ObservableDict.getattr AttributeError:'超级' 对象没有属性 'getattr'

kivy kivy-language kivymd
1个回答
0
投票

您可以将

ListProperty
添加到
MainWindow
来定义
Rectangle
位置。那么
rect_pos()
方法就可以返回该
ListProperty
的值:

class MainLayout(BoxLayout):
    rect_pos = ListProperty([0, 0])

    def rect_position(self):
        print(self.rect_pos)

在您的

kv
中,您可以使用
ListProperty
作为
Rectangle
位置:

<MainLayout>:
    orientation: "horizontal"
    rect_pos: (self.width/4 + 50, self.height*3/4)

    Label:
        canvas:
            Rectangle:
                pos: root.rect_pos
                size: (100, 0)

这还允许您通过更改

Rectange
的值来调整
ListProperty
位置。

© www.soinside.com 2019 - 2024. All rights reserved.