分配属性时,Kivy ids返回KeyError

时间:2018-11-29 19:26:26

标签: python python-2.7 kivy

我试图在kivy 1.10.1框架中创建一个函数,该函数在理论上将由多个圆圈组成。它使用给定半径的参数形式来计算球心的位置。在这种情况下,我想为字母表中的每个字母画一个圆圈。我为每个字母制作了一个新的Letter小部件,但是每当它尝试添加位置属性时,它都会返回一个KeyError: 'A',其中包含我想获取的键(我认为我在self.add_widget(Letter(id=letter))中分配了该键)

Main.py:

from kivy.app import App
from kivy.uix.widget import Widget
import math
import string


class Letter(Widget):
    pass


class MainWidget(Widget):
    def __init__(self, **kwargs):
        super(MainWidget, self).__init__(**kwargs)

        theta = 0
        for letter in string.uppercase:
            coord_x = 100 * math.cos(theta)
            coord_y = 100 * math.sin(theta)

            self.add_widget(Letter(id=letter))
            self.ids[letter].center_x = coord_x
            self.ids[letter].center_y = coord_y

            theta += 360./float(len(string.uppercase))


class MainApp(App):
    def build(self):
        return MainWidget()


if __name__ == '__main__':
    MainApp().run()

Main.kv:

#:kivy 1.10.1

<Letter>:
    size: 50,50
    canvas:
        Color:
            rgb: 0,0,0
        Ellipse:
            pos: self.pos
            size: self.size

<MyWidget>:
    canvas:
        Rectangle:
            pos: self.pos
            size: self.size

1 个答案:

答案 0 :(得分:0)

self.ids仅保存在kv中创建的窗口小部件的ID。在Python中您不需要它,因为您已经对小部件有了方便的引用:

l = Letter()
self.add_widget(l)
l.center_x = coord_x
l.center_y = coord_y