from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.scrollview import ScrollView
from kivy.effects.scroll import ScrollEffect
from kivy.uix.widget import Widget
from kivy.uix.button import Button
class BSGameMain(BoxLayout):
blmain = BoxLayout(orientation = 'vertical') # MainBoxLayout init
scrlFBtns = ScrollView(effect_cls = 'ScrollEffect')
blbtns = BoxLayout(
orientation = 'vertical',
size_hint_y = None
) # BoxLayout for buttons
blbtns.bind(minimum_height = blbtns.setter('height'))
scrlFBtns.add_widget(blbtns)
for i in range (2):
blbtns.add_widget(Button(
text='asd',
size_hint_y = None,
height = 40
))
lblmain = Label(text = 'asd')
blmain.add_widget(lblmain)
blmain.add_widget(scrlFBtns)
class BSApp(App):
def build(self):
game = BSGameMain()
return game.blmain
if __name__ == "__main__":
BSApp().run()
考虑到滚动视图,必须使按钮从下方显示,而不是从中间显示。我不能让他这样做。
答案 0 :(得分:0)
请记住BoxLayouts会覆盖对定位的修改,因为它们会自动定位子项。这使得他们非常自给自足,但有点顽固地工作。
就像你说的那样,如果只有几个按钮,它会粘在中间。滚动视图可以工作,但由于它是一个boxlayout的子项,它只能伸展到boxlayout所能说的范围,即窗口的下半部分。此外,由于按钮的boxlayout自上而下增加了孩子,这就是你的按钮出现在中间的原因。实际上,它会将按钮添加到窗口下半部分的顶部。
您指定了boxlayouts,其中不需要boxlayouts。您可能想要的一件事是根据滚动视图中的按钮数量随意定位滚动视图。这将需要if语句和整数。
我的更改:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.core.window import Window
from kivy.uix.scrollview import ScrollView
from kivy.effects.scroll import ScrollEffect
from kivy.uix.widget import Widget
from kivy.uix.button import Button
class BSGameMain(): #No longer a boxlayout.
scroll_height = 0;
blmain = Widget() #No longer a boxlayout. Fills the window.
blbtns = BoxLayout(
orientation = 'vertical',
size_hint = (1, None),
) # BoxLayout for buttons
blbtns.bind(minimum_height = blbtns.setter('height'))
for i in range (20): #number of buttons printed
blbtns.add_widget(Button(
text='asd',
size_hint_y = None,
height = 40
))
if (scroll_height < (Window.height / 2)):
scroll_height = scroll_height + 40 #This measures how much space we need for the scrollview. Make sure it matches button height!
scrlFBtns = ScrollView(effect_cls = 'ScrollEffect', pos = (0, 0), size = (Window.width, scroll_height))
#The pos of 0,0 ensures scrlFBtns stays at the bottom. Place at negative coordinates if you want it to extend off-screen.
scrlFBtns.add_widget(blbtns)
lblmain = Label(text = 'asd', halign = 'center', y = (Window.height * 0.75), width = Window.width, color = (1,1,1,1))
blmain.add_widget(lblmain)
blmain.add_widget(scrlFBtns)
class BSApp(App):
def build(self):
game = BSGameMain()
return game.blmain
if __name__ == "__main__":
BSApp().run()
结果:
一键
,
三个按钮
,
二十个按钮
希望这与你正在寻找的东西一致!