【问题标题】:Kivy - Parsing structure to widgetKivy - 将结构解析为小部件
【发布时间】:2017-04-09 15:48:52
【问题描述】:

我在将数据结构解析为 Kivy 中的小部件时遇到问题,该小部件将访问该结构并能够在屏幕上显示一个值,并通过时钟间隔不断更新(不确定更好的做法这还没有)。

我在下面的(非工作)代码中突出显示了问题:

ma​​in.py

from kivy.app import App
from test import TestWidget

class TestApp(App):

    def build(self):
        testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3}

        # Issue here parsing the table like this?
        return TestWidget(testStructTable)

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

test.py

from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.relativelayout import RelativeLayout
from kivy.properties import NumericProperty


class TestWidget(RelativeLayout):

    def __init__(self, testStructTable, **kwargs):
        super(TestWidget, self).__init__(**kwargs)
        Builder.load_file('test.kv')

        sm = ScreenManager()
        sm.add_widget(MainScreen(name='MainScreen'))
        self.add_widget(sm)

        # Error accessing the table
        print self.testStructTable

        # Have the update_test_val continuously called
        #Clock.schedule_interval(MainScreen.update_test_val(testStructTable), 1 / 60)


class MainScreen(Screen):

    def __init__(self, **kwargs):
        testVal = NumericProperty(0)

    def update_test_val(self, testStructTable):
        # Get testVal from testStructTable
        # Something like:
        # self.testVal = testStructTable.testVal + 1 ?
        self.testVal = self.testVal + 1

test.kv

<MainScreen>:
    FloatLayout:
        Label:
            text: str(root.testVal)
            font_size: 80

我的目标是通过访问该数据结构让 testVal 在屏幕上不断更新,但是我目前无法实现这一点,您能否建议?

【问题讨论】:

    标签: python data-structures kivy


    【解决方案1】:

    在您的__init__ 方法中,您传递了testStructTable,然后您尝试访问self.testStructTable,在您明确分配之前不存在:

    from kivy.app import App
    from kivy.lang import Builder
    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.uix.relativelayout import RelativeLayout
    from kivy.properties import NumericProperty
    
    
    class TestWidget(RelativeLayout):
        def __init__(self, testStructTable, **kwargs):
            super(TestWidget, self).__init__(**kwargs)
    
            print(testStructTable)
            self.testStructTable = testStructTable
            print(self.testStructTable)
    
    
    class TestApp(App):
        def build(self):
            testStructTable = {'randomVal1': 1, 'testVal': 2, 'randomVal2': 3}
            # Issue here parsing the table like this?
            return TestWidget(testStructTable)
    
    if __name__ == '__main__':
        TestApp().run()
    

    【讨论】:

    • 成功了,谢谢!您能否建议如何让 testVal 在屏幕上不断更新?
    • 将属性与kivy.clock 模块结合使用是一种正确的方法。 kivy 中的属性实现了观察者模式,因此对它们的任何更改都可以立即反映在您的小部件中。有关示例,请参见 here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2017-10-26
    • 2020-03-15
    • 2018-05-16
    相关资源
    最近更新 更多