在kivy中打开屏幕后如何应用DictProperty中的值?
我正在尝试从多个屏幕收集数据并显示在最后一个“结果”屏幕上。为此,我想将不同小部件的值存储在 dict 属性中并将它们显示在屏幕上。最小演示:
.py:
from kivy.app import App
from collections import defaultdict
from kivy.uix.widget import Widget
from kivy.properties import (
NumericProperty, ReferenceListProperty, ObjectProperty, DictProperty
)
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager, Screen
import pickle
import kivy
class ResultScreen(Screen):
results = DictProperty({})
def get_values(self):
self.results = {1 : -1, 2 : -2}
class PongScreen(Screen):
pass
class TestApp(App):
def build(self):
sm = ScreenManager()
# print(f'------------{sm.manager}--------------')
sm.add_widget(PongScreen(name='menu'))
sm.add_widget(ResultScreen(name='result'))
return sm
TestApp().run()
.kv:
#:kivy 1.0.9
#:import Factory kivy.factory.Factory
<ResultScreen>:
on_enter: self.get_values()
BoxLayout:
orientation : 'vertical'
BoxLayout:
orientation : 'horizontal'
BoxLayout:
orientation : 'vertical'
Label:
text: str(root.results.keys())
<PongScreen>:
BoxLayout:
Button:
text: 'To results'
on_press: root.manager.current = 'result'
Button:
text: 'Exit'
on_press: app.stop()
我希望在 ResultScreen
上的 Label
文本上获得 [1, 2]
。但是我得到的是空列表。据我了解,发生这种情况是因为初始化是在执行 get_values 函数之前进行的。如何显示所需的值?
I am trying to collect data from several screens and display on last 'result' screen. For that I want to store values of different widgets in dict property and display them on the screen. The minimum demonstration:
.py:
from kivy.app import App
from collections import defaultdict
from kivy.uix.widget import Widget
from kivy.properties import (
NumericProperty, ReferenceListProperty, ObjectProperty, DictProperty
)
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.screenmanager import ScreenManager, Screen
import pickle
import kivy
class ResultScreen(Screen):
results = DictProperty({})
def get_values(self):
self.results = {1 : -1, 2 : -2}
class PongScreen(Screen):
pass
class TestApp(App):
def build(self):
sm = ScreenManager()
# print(f'------------{sm.manager}--------------')
sm.add_widget(PongScreen(name='menu'))
sm.add_widget(ResultScreen(name='result'))
return sm
TestApp().run()
.kv:
#:kivy 1.0.9
#:import Factory kivy.factory.Factory
<ResultScreen>:
on_enter: self.get_values()
BoxLayout:
orientation : 'vertical'
BoxLayout:
orientation : 'horizontal'
BoxLayout:
orientation : 'vertical'
Label:
text: str(root.results.keys())
<PongScreen>:
BoxLayout:
Button:
text: 'To results'
on_press: root.manager.current = 'result'
Button:
text: 'Exit'
on_press: app.stop()
I expect to get [1, 2]
on the text of Label
on ResultScreen
. However I am getting empty list. As far as I understand it happens because initialization takes place before execution of get_values
function. How can I display desired values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论