【问题标题】:How can I change a value of pos_hint after clicking on the button?单击按钮后如何更改 pos_hint 的值?
【发布时间】:2019-07-17 23:47:57
【问题描述】:

我有 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

我该怎么做?

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    不幸的是,在您的代码中使用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()
    

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多