Python Kivy 条件设计在kv文件中

2024-06-02 05:28:51 发布

您现在位置:Python中文网/ 问答频道 /正文

在Kivy中,类似于下面例子的方法是否可行?
发布的代码显然不起作用,这只是一个例子:我需要根据特定属性绘制不同的布局。在

你建议怎么解决这个问题?在

BoxLayout:
    number: 0
    if self.number > 3:
        Label:
            text: 'number is bigger than 3'
        Button:
            text: 'click here to decrease'
            on_press: root.number -= 1
    else:
        Label:
            text: 'number is smaller than 3'
        Button:
            text: 'click here to increase'
            on_press: root.number += 1

Tags: to方法textnumberhereisonbutton
2条回答

KV-lang的功能有限,因此如果您想要更多的控制,您应该将您的逻辑放在Python代码中。例如,您可以将布局移动到单独的小部件中,然后使用add_widget()remove_widget()从Python代码中动态地选择一个合适的小部件。在

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import Builder

Builder.load_string('''
<SubWidget1>:
    Label:
        text: 'number is bigger than 3'
    Button:
        text: 'click here to decrease'
        on_press: root.parent.number -= 1

<SubWidget2>:
    Label:
        text: 'number is smaller than 3'
    Button:
        text: 'click here to increase'
        on_press: root.parent.number += 1

<MyWidget>
    number: 0
''')

class SubWidget1(BoxLayout):
    pass

class SubWidget2(BoxLayout):
    pass

class MyWidget(BoxLayout):
    number = NumericProperty()

    def __init__(self, *args):
        super(MyWidget, self).__init__(*args)
        self.widget = None
        self._create_widget()

    def _create_widget(self):
        print(self.number)
        if self.widget is not None:
            self.remove_widget(self.widget)
        if self.number > 3:
            self.widget = SubWidget1()
        else:
            self.widget = SubWidget2()
        self.add_widget(self.widget)

    def on_number(self, obj, value):
        self._create_widget()

class MyApp(App):
    def build(self):
        return MyWidget()

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

我会选择屏幕管理器或旋转木马,一个简单的例子可能是:

Carousel: 
    index: 1# or a "certain property" :)
    scroll_timeout: 0.0 # disable the user ability to mess with the widgets layout 
    BoxLayout: #first option
        Label:
        Button:
    BoxLayout: #2nd option
        Button:
        Label:

如果您将索引绑定到您选择的属性,它将自动切换布局:)。。。在

基于屏幕管理器的方法将非常相似,主要的变化是只绑定当前屏幕属性,而不是索引

相关问题 更多 >