应用pos_hint后获取小部件XY位置

时间:2013-08-04 11:34:27

标签: python kivy

使用pos_hint定位小部件(例如Scatter)后,如何获取当前的x,y位置(pos)?

e.g。

wid.pos = (250, 350)
print wid.pos  <----- # it print (200, 350). Correct.
wid.pos_hint = {'top':0.9, 'right':0.5}  # moved the widget to other position using pos_hint.
print wid.pos  <----- # it sill print (200, 350) eventhough the widget position has changed.


编辑:示例代码

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scatter import Scatter

Builder.load_string(""" 
<Icon@Scatter>: 
    size_hint: .06, .08

    Image:
        size: root.size
        allow_stretch: True
        keep_ratio: True
""")

class Icon(Scatter):
    def __init__(self, **kwargs):
        self.pos = (200, 200)
        self.move()
        super(Icon, self).__init__(**kwargs)

    def move(self):
        print "BEFORE: "
        print self.pos      # print 200, 200
        self.pos_hint = {'top':0.9, 'right':0.5} # assume now Scatter has moved to x800 y500.
        print "AFTER: "
        print self.pos      # it still print 200, 200 :(


class GameApp(App):
    def build(self):
        return Icon()

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

1 个答案:

答案 0 :(得分:1)

问题是在分配布局所遵循的值(例如size_hintpos_hint)后,窗口(以及布局本身)不会立即刷新。它们在窗口刷新后更新(直到方法结束)

您基本上可以明确调用方法do_layout。文档说“当需要布局时,通过触发器调用此方法”。我不得不说,我不确定是否明确地调用它可能会导致一些问题,因为这种用法没有记录。它对我有用,但要小心:

wid.pos = (250, 350)
print wid.pos  # it prints (200, 350). Correct.
wid.pos_hint = {'top':0.9, 'right':0.5} 
print wid.pos  # it sill print (200, 350) 
wid.do_layout()
print wid.pos  # it should work now

当您让窗口刷新时,即在您实际看到Scatter(或任何其他Widget)移动后,这不是必需的。


编辑:问题中代码的更正版本

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.scatter import Scatter
from kivy.uix.floatlayout import FloatLayout

Builder.load_string(""" 
<Icon>: 
    size_hint: .06, .08

    Image:
        size: root.size
        allow_stretch: True
        keep_ratio: True

<BaseLayout>:
    icon: _icon
    Icon:
        id: _icon
    Button: 
        text: "Press me"
        size_hint: .1,.05
        on_press: _icon.move()
""")

class Icon(Scatter):
    def __init__(self, **kwargs):
        self.pos = (200, 200)
        super(Icon, self).__init__(**kwargs)

    def move(self):
        print "BEFORE: "
        print self.pos      # print 200, 200
        self.pos_hint = {'top':0.9, 'right':0.5} # assume now Scatter has moved to x800 y500.
        self.parent.do_layout()
        print "AFTER: "
        print self.pos      # it still print 200, 200 :(


class BaseLayout(FloatLayout):
    pass


class GameApp(App):
    def build(self):
        return BaseLayout()

if __name__ == '__m
ain__':
    GameApp().run()