Kivy GUI - 填充圆圈中的颜色,如水填充圆形容器级别

时间:2018-03-12 12:51:50

标签: python kivy

enter image description here

如上图所示,我需要在Kivy GUI中编写一个.kv文件,这样我就可以显示一个填充颜色的圆圈作为值增加。对于0值,它为空,因为值增加圆填充颜色。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

通过为此创建掩码可以实现这种效果,您可以使用Stencil instructions,如下所示:

from kivy.app import App
from kivy.lang import Builder

main_widget_kv = '''
BoxLayout:
    border: 10
    WaterFill:
        level: slider.value_normalized
        color: 1, 1, 0
    Slider:
        id: slider
        orientation: 'vertical'
        value: 50

<WaterFill@Widget>:
    level: 0.1
    width: self.height
    size_hint: None, 1
    color: 0, 0, 1
    canvas:
        StencilPush
        Ellipse:
            pos: root.pos
            size: root.size

        StencilUse

        Color:
            rgb: root.color
        Rectangle:
            pos: root.pos
            size: (root.width, root.level*root.height)

        StencilUnUse

        StencilPop
'''

class TestApp(App):
    def build(self):
        return Builder.load_string(main_widget_kv)

if __name__ == '__main__':
    TestApp().run()

enter image description here

<强>更新

以下示例显示了如何在Clock的帮助下使用方法更新高度值的示例:

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.uix.anchorlayout import AnchorLayout
from kivy.lang import Builder

Builder.load_string("""
<WaterFill>:
    level: 0.0
    width: self.height
    size_hint: None, 1
    color: 0, 0, 1
    canvas:
        StencilPush
        Ellipse:
            pos: root.pos
            size: root.size
        StencilUse
        Color:
            rgb: root.color
        Rectangle:
            pos: root.pos
            size: (root.width, root.level*root.height)
        StencilUnUse
        StencilPop
""")


class WaterFill(Widget):
    def __init__(self, *args, **kwargs):
        Widget.__init__(self, *args, **kwargs)
        self.delta = 0.01

        Clock.schedule_interval(self.on_timeout, 0.05)

    def on_timeout(self, *args):
        self.level += self.delta
        if self.level >= 1:
            self.delta = -0.01
        elif self.level <= 0:
            self.delta = 0.01


class TestApp(App):
    def build(self):
        lay = AnchorLayout(anchor_x='center', anchor_y='center')
        lay.add_widget(WaterFill())
        return lay


if __name__ == "__main__":
    TestApp().run()