我想在for循环中创建的动态按钮中显示Image +标签。问题是它只在最后一个按钮显示图像+标签布局。如何在所有按钮中显示它?
main.py
class HomeScreen(Screen):
grid_l = ObjectProperty(None)
top_lbl = ObjectProperty(None)
def search_btn_pressed(self):
grid = self.grid_l
grid.bind(minimum_height=grid.setter('height'),
minimum_width=grid.setter('width'))
for i in range(3):
layout = GridLayout(cols=1)
print layout
img = Image(source='kivy.png')
print img
lbl = Label(text='label')
layout.add_widget(img)
layout.add_widget(lbl)
btn1 = Button(size_hint=(1, None))
btn1.text = '%r' % i
btn1.add_widget(layout)
grid.add_widget(btn1)
.kv
#:kivy 1.7.2
<HomeScreen>:
scroll_view: scrollviewID
top_lbl: lblID
grid_l: gridlayoutID
AnchorLayout:
size_hint: 1, .1
pos_hint: {'x': 0, 'y': .9}
anchor_x: 'center'
anchor_y: 'center'
Label:
id: lblID
text: 'Button Tester'
Button:
size_hint: 1, .1
pos_hint: {'x': 0, 'y': .8}
text: 'Press me!'
on_release: root.search_btn_pressed()
ScrollView:
id: scrollviewID
orientation: 'vertical'
pos_hint: {'x': 0, 'y': 0}
size_hint: 1, .8
bar_width: '8dp'
GridLayout:
id: gridlayoutID
cols: 1
size_hint: 1, None
row_default_height: 40
row_force_default: False
答案 0 :(得分:4)
它实际上并不仅仅显示最后一个按钮 - 它显示每个按钮,但位于相同的位置。问题是Button
不是布局,因此不会执行其子项的布局。因此,每个按钮的GridLayout
都会在0, 0
处呈现,其大小为100, 100
,相对于最近的相对父级的原点(在这种情况下,GridLayout
grid_l
因为它包含在ScrollView
)中。
将窗口小部件添加到非布局窗口小部件时,您可以通过设置位置和大小来布局这些窗口小部件。请注意,您必须设置实际的pos
(或x
和y
)和size
(或width
和height
) - 您无法使用pos_hint
或size_hint
,因为这些仅由布局处理。
可以使用dynamic classes中的kv language轻松完成此操作:
<CustomButton@Button>:
image_source: ''
subtext: ''
GridLayout:
height: self.parent.height # match the button's height
width: 100 # set to whatever you would like
pos: self.parent.pos # match the button's position
cols: 1
Image:
source: root.image_source
Label:
text: root.subtext
要使用动态类,您需要导入Factory
:
from kivy.factory import Factory
然后,在你的循环中:
for i in range(3):
btn = Factory.CustomButton(text=str(i), size_hint=(1, None),
image_source='kivy.png', subtext='label')
grid.add_widget(btn)
最后,请注意:每次调用grid_l
时,您都会在search_btn_pressed()
上创建新的绑定。这些绑定只应创建一次。您可以通过将这些绑定移动到HomeScreen.__init__()
来在Python中绑定一次,但同样,这在kv中更容易:
GridLayout:
id: gridlayoutID
cols: 1
size_hint: 1, None
row_default_height: 40
row_force_default: False
height: self.minimum_height # bind height to minimum_height
width: self.minimum_width # bind width to minimum_width