我正在使用 Python kivy 制作 GUI。 我想在启动时在 GUI 上显示一个随机值。
我认为应该在 __init__ 函数中完成,并尝试了以下代码。
测试.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()
测试.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__'
最佳答案
问题是 TestWidget 构造函数在 .kv 之前使用,因此 id“spinner_test”当时不存在。
鉴于此,一个可能的解决方案是在显示 GUI 后立即进行更改:
# ...
<b>from kivy.clock import Clock</b>
# ...
class TestWidget(Widget):
def __init__(self, **kwargs):
super(TestWidget, self).__init__(**kwargs)
<b>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)]
# ...</b>
另一个选项是创建一个 ListProperty,在其中设置值,然后与 Spinner 的“values”属性进行绑定(bind):
TestWidget:
<TestWidget>:
BoxLayout:
size:root.size
orientation: 'vertical'
Spinner:
id:spinner_test
text: ""
values: root.values # <---
Label:
text: ""
Label:
text: ""
Label:
text: ""
# ...
<b>from kivy.properties import ListProperty</b>
# ...
class TestWidget(Widget):
<b>values = ListProperty()</b>
def __init__(self, **kwargs):
super(TestWidget, self).__init__(**kwargs)
first = random.random()
second = random.random()
third = random.random()
<b>self.values = [str(first), str(second), str(third)]</b>
# ...
关于python - 如何使用Python kivy在启动时确定Spinner值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58182111/