我想构建一个屏幕,在该屏幕上按下按钮时,标签的大小和位置会发生变化:
Button : Changes
x++ -> x co-ordinate of label increments by 0.1 in pos_hint property
x-- -> x co-ordinate of label decrements by 0.1 in pos_hint property
到目前为止,我已经尝试过了,
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.scatter import Scatter
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
class Screen(Widget):
lbl = ObjectProperty(None)
def __init__(self, **kwargs):
super(Screen, self).__init__(**kwargs)
self.count_x = 0.1
def print_pos_change(self,instance,value):
print(instance,"Moved to", value)
def callback(self,arg):
if arg == "x++":
self.count_x+=0.1
self.lbl.pos_hint["x"] = self.count_x
elif arg == "x--":
self.count_x-=0.1
self.lbl.pos_hint["x"] = self.count_x
class WidgetEx(App):
kv_directory = "kv-files"
def build(self):
return Screen()
if __name__ == "__main__":
WidgetEx().run()
这是kv文件,
<Screen>
lbl:lbl
FloatLayout:
size:root.width,root.height
Label:
id:lbl
text:"Hello"
size_hint:0.5,0.5
on_pos:root.print_pos_change(self,self.pos)
canvas:
Color:
rgba: 0, 0, 1, 1
Rectangle:
pos:self.pos
size:self.size
GridLayout:
cols:2
size_hint:1,0.1
Button:
text:"x++"
on_press:root.callback("x++")
Button:
text:"x--"
on_press:root.callback("x--")
现在的问题是位置不变,更改期间也不会调用print_pos_change
。
我知道我可以直接使用self.lbl.x
和self.lbl.y
,但是我想使用self.lbl.pos_hint
进行更改。我该怎么办??
这是UI的ss,
在方法do_layout()
的结尾处,我已将floatlayout
用于callback
,但是按钮现在也随标签一起移动了?我该如何解决?
为什么size_hint正常工作而pos_hint不起作用?它背后有逻辑吗?
我想增加pos_hint["x"]
属性以使每次按下x++
按钮增加0.1。
答案 0 :(得分:0)
有很多方法可以做到这一点。
尝试在pos提示右侧和顶部使用数字属性。
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty
from kivy.lang import Builder
KV = """
MyWidget:
FloatLayout:
size:root.width,root.height
Label:
text:"Hello"
size_hint:0.5,0.5
pos_hint: {"top":root.pos_hint_top, "right":root.pos_hint_right}
canvas.before:
Color:
rgba: 0, 0, 1, 1
Rectangle:
pos:self.pos
size:self.size
GridLayout:
cols:2
size_hint:1,0.1
Button:
text:"x++"
on_press:root.callback("x++")
Button:
text:"x--"
on_press:root.callback("x--")
"""
class MyWidget(Widget):
pos_hint_right = NumericProperty(0.5)
pos_hint_top = NumericProperty(0.5)
def callback(self,arg):
if arg == "x++":
self.pos_hint_right += 0.1
elif arg == "x--":
self.pos_hint_right -= 0.1
class WidgetEx(App):
def build(self):
return Builder.load_string(KV)
if __name__ == "__main__":
WidgetEx().run()