【问题标题】:Kivy position of a GridLayout's children always returns (0,0)GridLayout 子项的 Kivy 位置始终返回 (0,0)
【发布时间】:2016-09-16 17:48:19
【问题描述】:

当我向我的 GridLayout 添加一些元素时,如果想要获取元素位置,Kivy 总是返回 (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)?我究竟做错了什么?

这是我得到的:

但我希望每个“hello”字符串前面都有“foo”字符串。

我该怎么做?

【问题讨论】:

    标签: python python-3.x kivy kivy-language


    【解决方案1】:

    当您打印时,在 kivy GUI 循环的第一帧,pos 等于 [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')))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2020-03-24
      • 1970-01-01
      • 2012-07-30
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多