单击按钮后如何更改pos_hint的值?

时间:2019-07-17 23:47:57

标签: python kivy kivy-language

我有MainScreen类。单击“下一步”功能中的按钮后,需要移动图片。我正在尝试在“下一个”功能中设置一个新值,但不会更改该值。

class MainScreen(Screen):

    btns = ObjectProperty(None)
    img = ObjectProperty(None)

    pic_pos = -0.8

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)

        self.pic = Image(source='img/icon-back.png', pos_hint={'x': self.pic_pos, 'y': 0})
        self.img.add_widget(self.pic)


    def on_btns(self, *args):
        for x in word_list:
            self.btn = Button(text=x)
            self.btn.bind(on_press=self.next)
            self.btns.add_widget(self.btn)

    # here I am trying to change the value
    def next(self, instance):
        self.pic_pos = 0.3

我该怎么做?

1 个答案:

答案 0 :(得分:2)

不幸的是,在代码中使用self.pic_pos并没有设置任何绑定,因此您的pos_hint设置为{'x': -0.8, 'y': 0},并且更改self.pic_pos无效。要做的是使用kv来利用kv为您设置的绑定。另一种方法是将绑定自己设置为:

class MainScreen(Screen):

    btns = ObjectProperty(None)
    img = ObjectProperty(None)
    pic_pos = NumericProperty(-0.8)

    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)

        self.pic = Image(source='tester.png', pos_hint={'x': self.pic_pos, 'y': 0})
        self.bind(pic_pos=self.handle_pos_hint_change)

    def handle_pos_hint_change(self, instance, value):
        self.pic.pos_hint['x'] = value
        self.do_layout()