(1)通过使用以下KV文件版本是能够把BorderImage
widget在指定位置..
<Screen>:
ProgressBar:
max: 100
pos_hint: {'top':0.86, 'x':0.01}
size_hint_x: 0.49
size_hint_y: 0.1
canvas:
BorderImage:
border: (10, 10, 10, 10)
pos: self.x, self.center_y
size: self.width, 8
source: '0.png'
(2)但是,应该实现相同的功能,(1)不工作properly.BorderImage
widget下面纯Python代码被放置在屏幕的底部。 pos_hint={'top':0.86,'x':0.01}
不起作用。我认为,如何指定pos=(bar.x, bar.center_y)
因为bar.center_y
值来自代码不同的是不好的(1)。
class BarWidget(FloatLayout):
def __init__(self, **kwargs):
super(BarWidget, self).__init__(**kwargs)
self.build()
def build(self):
bar = ProgressBar(pos_hint={'top':0.86,'x':0.01}, max=100, size_hint_x=0.49, size_hint_y=0.1)
with bar.canvas:
BorderImage(border=(10, 10, 10, 10), pos=(bar.x, bar.center_y), size=(self.width/2, 8), source='0.png')
self.add_widget(bar)
我应该如何修改bar.center_y
?
在KV语言,当你设置像size: self.size
一个属性,这个属性被自动引入“自我”窗口小部件改变形状的大小来更新。当事情在屏幕/布局加载了,他们开始与时髦的位置和大小,然后移动到正确的。由于事情在改变尺寸/位置,如果你在工作KV自动更新,它可以作为你的期望。
在Python中,你必须明确地绑定一些功能,如果控件的大小或位置它是从继承改变它的大小和POS更新画布。您可以通过使用bind
功能(在大多数/所有kivy部件可用)做到这一点。使用bind
,你可以说bind(<attribute>=<function>)
这意味着随时widget的<attribute>
,又名大小或POS,改变,它调用<function>
我没有,因为不是所有的帐正好与你的代码进行测试,但是这是我为我的项目做。让我知道它是如何工作的。如果它不工作,编辑你的答案是的代码,我可以复制/粘贴一起工作的一个片段,我会更新我的答案。
class BarWidget(FloatLayout):
def __init__(self, **kwargs):
super(BarWidget, self).__init__(**kwargs)
self.build()
def build(self):
# Make it so you can reference the bar and border image later
self.bar = ProgressBar(pos_hint={'top':0.86,'x':0.01}, max=100, size_hint_x=0.49, size_hint_y=0.1)
with self.bar.canvas:
# Make it so you can reference the border image
self.border_image = BorderImage(border=(10, 10, 10, 10), pos=(bar.x, bar.center_y), size=(self.width, 8), source='0.png')
self.add_widget(self.bar)
# Make it so whenever the widget's pos or size changes, we update the border image
self.bar.bind(pos=self.update_border_image, size=self.update_border_image)
# make a function to update border image
def update_border_image(self, *args):
self.border_image.size = (self.width, 8) # Should this 8 be 0.8 by the way?
self.border_image.pos = (self.bar.x, self.bar.center_y)