我无法在Kivy ScreenManager的屏幕上放置AccordionItem。为此,我必须定义类似root = Accordion()的名称。但是我不知道ScreenLayout在哪里定义。我用纯python构建它,因为我是Kivy的新手,但不是python的新手。
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.accordion import Accordion, AccordionItem
class ScreenOne(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
btn1 = Button(
text='change screen',
size_hint=(.5, .05),
pos_hint={'left':0, 'top':1}
)
btn1.bind(on_press=self.changer)
self.add_widget(btn1)
def changer(self,*args):
self.manager.current = 'screen2'
def test(self,instance):
print('This is a test')
class ScreenTwo(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
btn2 = Button(
text='change screen',
size_hint=(.5, .25),
pos_hint={'left':0, 'top':1}
)
btn2.bind(on_press=self.changer)
self.add_widget(btn2)
title = ["Title 1", "Title 2","Title 3","Title 4","Title 5"]
for x in range(5):
item = AccordionItem(title= title[x])
item.add_widget(Label(text='Very big content\n' * 10))
self.add_widget(item)
return sm
def changer(self,*args):
self.manager.current = 'screen1'
def test(self,instance):
print('This is another test')
class TestApp(App):
def build(self):
sm = ScreenManager()
sc1 = ScreenOne(name='screen1')
sc2 = ScreenTwo(name='screen2')
sm.add_widget(sc1)
sm.add_widget(sc2)
print (sm.screen_names)
return sm
if __name__ == '__main__':
TestApp().run()
ScreenTwo应该显示5个AccordionItems。但是它们重叠并且不能正常工作。
答案 0 :(得分:0)
默认情况下,Screen不显示任何内容:它只是RelativeLayout。因此,为了在第二个屏幕中显示Button和Accordion小部件,您需要将这两个小部件包含在layout中,例如BoxLayout。
以下片段说明了如何使用BoxLayout
小部件来封装Button
和Accordion
小部件。
from kivy.uix.boxlayout import BoxLayout
...
class ScreenTwo(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
layout = BoxLayout(orientation='vertical') # instantiate BoxLayout
self.add_widget(layout) # add BoxLayout to screen
btn2 = Button(
text='change screen',
size_hint=(.5, .05),
)
btn2.bind(on_press=self.changer)
layout.add_widget(btn2) # add Button to BoxLayout
title = ["Title 1", "Title 2", "Title 3", "Title 4", "Title 5"]
accordion = Accordion() # instantiate Accordion
layout.add_widget(accordion) # add Accordion to BoxLayout
for x in range(5):
item = AccordionItem(title=title[x])
item.add_widget(Label(text='Very big content\n' * 10))
accordion.add_widget(item) # add AccordionItem to Accordion