单击按钮后如何更改 pos_hint 的值?
How can I change a value of pos_hint after clicking on the button?
我有 MainScreen class。单击 'next' 功能中的按钮后,我需要移动图片。我正在尝试在 'next' 函数中设置一个新值,但它不会更改该值。
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
我该怎么做?
不幸的是,在您的代码中使用 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()
我有 MainScreen class。单击 'next' 功能中的按钮后,我需要移动图片。我正在尝试在 'next' 函数中设置一个新值,但它不会更改该值。
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
我该怎么做?
不幸的是,在您的代码中使用 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()