Python Kivy将ScrollView添加到屏幕

时间:2018-07-07 12:08:14

标签: python python-3.x kivy

注意:我正在使用another discussion on StackOverflow中的代码。

此代码可以按原始方式很好地工作,并返回带有适当小部件的布局:

Original Code Result

但是,一旦我使用此方法添加屏幕:

import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.graphics import Color, Rectangle
from kivy.uix.screenmanager import ScreenManager, Screen


class MyScreenManager(ScreenManager):
    pass


class TestScreen(Screen):
    pass


class Main(App):
    def build(self):
        layout = FloatLayout()
        layout.add_widget(Scroller())
        TestScreen().add_widget(layout)
        MyScreenManager().add_widget(screen=TestScreen(name='TestScreen'))

        return MyScreenManager()


class Scroller(ScrollView):
    def __init__(self):
        ScrollView.__init__(self)
        layout = GridLayout(cols=1, size_hint=(1, None))
        self.add_widget(layout)
        layout.bind(minimum_height=layout.setter('height'))

        for i in range(20):
            layout.add_widget(Field('Test field {}'.format(i), i%2 is 0))


class Field(GridLayout):
    def __init__(self, name, bg):
        assert isinstance(name, str)
        assert isinstance(bg, bool)
        self.bg = bg
        GridLayout.__init__(self,
                            rows = 1,
                            padding = 10,
                            size = (0, 60),
                            size_hint = (1, None))
        self.add_widget(Label(text = name))
        self.add_widget(Button(text = 'Test',
                               size = (200, 0),
                               size_hint = (None, 1)))
        self.bind(pos = self.change_background)
        self.bind(size = self.change_background)

    def change_background(self, *args):
        self.canvas.before.clear()
        with self.canvas.before:
            Color(.4, .4, .4, mode='rgb')
            Rectangle(size=self.size, pos=self.pos)

Main().run

我最终得到的是这样的东西:

Result of code after screens

如果有人可以帮助我,那就太好了!

1 个答案:

答案 0 :(得分:0)

解决方案

黑/空白窗口是由于未实例化TestScreen()和MyScreenManager()造成的。

class Main(App):
    def build(self):
        layout = FloatLayout()
        layout.add_widget(Scroller())
        testscreen = TestScreen(name='TestScreen')
        testscreen.add_widget(layout)
        root = MyScreenManager()
        root.add_widget(screen=testscreen)
        return root 

输出

Img01