【问题标题】:Kivy nested IDsKivy 嵌套 ID
【发布时间】:2015-10-27 04:46:53
【问题描述】:

我正在尝试创建一个客户管理软件,所以我需要创建一个GUI。我选择了Kivy,因为它是开源的,而LGPL

这个软件有多个面板,所以我需要ID 来访问每个面板中的小部件。我用kv语言创建了Kivy规则,但是当我嵌套一个类是另一个类时,我无法访问ID。下面是一个示例代码:

LayoutTestApp.py

from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.uix.boxlayout import BoxLayout


class SkipperList(GridLayout):
    pass


class TestPanel(BoxLayout):
    def __init__(self, **kwargs):
        super(TestPanel, self).__init__(**kwargs)
        print "TestPanel ids:", self.ids


class MasterPanel(TabbedPanel):
    pass


class NjordApp(App):
    def __init__(self, **kwargs):
        super(NjordApp, self).__init__(**kwargs)

    def build(self):
        root = MasterPanel()
        return root

if __name__ == '__main__':
    application = NjordApp()
    application.run()

njord.kv

#:kivy 1.9.0

<MasterPanel>
    pos_hint: {'center_x': .5, 'center_y': .5}
    do_default_tab: False

    TabbedPanelItem:
        text: 'Skippers'
        BoxLayout:
            padding: 10
            spacing: 10
            TestPanel:

<TestPanel>:
    id: SkipperPanelId
    BoxLayout:
        padding: 10
        spacing: 10
        BoxLayout:
            orientation: 'vertical'

            Label:
                text: 'List des mecs'
                size_hint: 1, 0.09
            Button:
                id: button_up
                size_hint: 1, 0.08
                text:'/\\'
            Button:
                id: button_down
                size_hint: 1, 0.08
                text:'\/'

当我启动软件时,打印只返回{}。 例如,有人可以告诉我如何访问 button_up ID 吗? 提前谢谢。

【问题讨论】:

    标签: python user-interface kivy


    【解决方案1】:

    您看不到 id 的原因是因为您在 TestPanel构造函数 中打印。它还没有完成创建,更不用说添加任何东西了。如果您在创建 GUI 后打印 ID(即,按下按钮),那么您将看到 ID:

    class TestPanel(BoxLayout):
        def __init__(self, **kwargs):
            super(TestPanel, self).__init__(**kwargs)
            print "TestPanel ids:", self.ids
    
        def test(self, *x):
            print self.ids
    
    
    ...
    
            Button:
                id: button_up
                size_hint: 1, 0.08
                text:'/\\'
                on_press: root.test()
    

    输出:

    {'button_down': <WeakProxy to <kivy.uix.button.Button object at 0x7f63159052c0>>, 'button_up': <WeakProxy to <kivy.uix.button.Button object at 0x7f63158f3738>>}
    

    【讨论】:

    • 非常感谢,我知道我做错了什么。现在,我怎么知道对象已经创建完成了?例如,如果我想在创建 TestPanel 时将按钮的文本初始化为某些内容,我可以这样做吗?再次感谢您的回答:)
    • 我不确定你的意思。你不能只将文本设置为你想要在 kv 中初始化它的内容吗?如果您想动态设置它,您可以使用StringProperty 并将按钮的文本绑定到该属性。在这种情况下,不需要在设置标签之前创建按钮(只需设置属性,kivy 将负责在创建按钮后更新按钮)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多