如何使用Python Kivy在启动时确定Spinner值

时间:2019-10-01 09:43:52

标签: python kivy kivy-language

我正在使用Python Kivy制作GUI。 我想在启动时在GUI上显示随机值。

我认为应该在__init__函数中完成此操作,并尝试了以下代码。

test.py

import random
from kivy.config import Config
from kivy.app import App
from kivy.uix.widget import Widget

Config.set('graphics', 'width', 300)
Config.set('graphics', 'height', 300)
Config.set('graphics', 'resizable', False)

class TestWidget(Widget):
    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)
        first = random.random()
        second = random.random()
        third = random.random()
        self.ids.spinner_test.values = [str(first),str(second),str(third)]

class TestApp(App):
    def __init__(self, **kwargs):
        super(TestApp, self).__init__(**kwargs)
        self.title = 'random value'

    def build(self):
        return TestWidget()

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

test.kv

TestWidget:

<TestWidget>:
    BoxLayout:
        size:root.size
        orientation: 'vertical'

        Spinner:
            id:spinner_test
            text: ""
            values: []

        Label:
            text: ""

        Label:
            text: ""

        Label:
            text: ""

但是,发生以下错误并且GUI无法启动。 我该如何修复代码?

 Traceback (most recent call last):
   File "kivy\properties.pyx", line 860, in kivy.properties.ObservableDict.__getattr__
 KeyError: 'spinner_test'

 During handling of the above exception, another exception occurred:

AttributeError: 'super' object has no attribute '__getattr__'

1 个答案:

答案 0 :(得分:0)

问题在于,TestWidget构造函数在.kv之前使用,因此ID“ spinner_test”当时不存在。

鉴于此,一种可能的解决方案是在显示GUI之后稍作更改:

# ...
from kivy.clock import Clock
# ...

class TestWidget(Widget):
    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)
        Clock.schedule_once(self.update)

    def update(self, *args):
        first = random.random()
        second = random.random()
        third = random.random()
        self.ids.spinner_test.values = [str(first), str(second), str(third)]

# ...

另一个选择是创建一个设置了值的ListProperty,然后使用Spinner的“ values”属性进行绑定:

TestWidget:

<TestWidget>:
    BoxLayout:
        size:root.size
        orientation: 'vertical'

        Spinner:
            id:spinner_test
            text: ""
            values: root.values # <---

        Label:
            text: ""

        Label:
            text: ""

        Label:
            text: ""
# ...
from kivy.properties import ListProperty

# ...


class TestWidget(Widget):
    values = ListProperty()

    def __init__(self, **kwargs):
        super(TestWidget, self).__init__(**kwargs)
        first = random.random()
        second = random.random()
        third = random.random()
        self.values = [str(first), str(second), str(third)]

# ...