2016-09-16 95 views
0

当我向GridLayout添加一些元素时,如果想要获取元素的位置,Kivy总是返回(0,0),但它不是真的,因为元素正确定位在我的窗户上。Kivy的GridLayout的子元素的位置总是返回(0,0)

class ImageButton(ButtonBehavior, Label): 

def __init__(self, *args, **kwargs): 
    super().__init__(*args, **kwargs) 
    self.text = 'hello' 

def add_sources(self, sources): 
    print(self.pos) #(0,0), but is not (0,0) 
    self.add_widget(Label(text='foo', pos=self.pos)) 

这是我的主要课程。

class MyClass(Widget): 

my_layout = ObjectProperty(GridLayout()) 

def __init__(self): 
    super().__init__() 
    self.load_layout() 

def load_map(self): 
    self.my_layout.rows = 2 
    self.my_layout.cols = 2 
    self.draw_ui() 

def draw_ui(self): 
    a = ImageButton() 
    b = ImageButton() 
    c = ImageButton() 
    d = ImageButton() 

    self.my_layout.add_widget(a) 
    self.my_layout.add_widget(b) 
    self.my_layout.add_widget(c) 
    self.my_layout.add_widget(d) 

    a.add_sources(0) 
    b.add_sources(1) 
    c.add_sources(0) 
    d.add_sources(1) 

为什么获取窗口小部件的位置会返回我(0,0)?我究竟做错了什么?

这就是我得到:

I'm getting this

但我想在每个“你好”字符串前的“foo”的字符串。

我该怎么做?

回答

0

当您打印它时,pos在kivy GUI循环的第一帧等于[0,0]。它稍后改变。你有两种方法可以解决这个问题:

  1. 等到第二帧时,pos按预期更新。
  2. 绑定pos,而不是在开始时只分配一次。

溶液1)例如:

from kivy.clock import mainthread 

class ImageButton(ButtonBehavior, Label): 
    ... 
    @mainthread 
    def add_sources(self, sources): 
     self.add_widget(Label(text='foo', pos=self.pos)) 

溶液2)例如:

class ImageButton(ButtonBehavior, Label): 
    ... 
    def add_sources(self, sources): 
     self.add_widget(Label(text='foo', pos=self.setter('pos'))) 
相关问题