感谢您的关注。我是Kivy / KivyMD /编程的新手,在python代码和kv代码之间我根本不了解某些基本知识。
我正在构建一个使用ScreenManager在两个屏幕之间切换的简单应用程序。 我计划在每个屏幕上创建一个动态生成的列表,其中包含来自数据库的数据。
我可以通过将静态列表和其他小部件放在kv文件中来添加它们。但是我似乎无法理解如何在python文件中的类中创建/更新数据并将其链接到kv文件ID。
在以下代码中,该程序正常运行,我在其中抛出了一个按钮,该按钮成功生成了一个列表,但目标是没有按钮,并在应用启动时自动生成列表。
我在尝试中添加了一些评论。我是使用错误的变量名还是做一些根本上错误的事情?
[main.py python文件]
paginate
[Multiscreen.kv文件]
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.list import OneLineListItem
class FirstWindow(Screen):
print('This prints automatically when App launches')
# But adding widgets doesn't happen automatically
# I tried variations but the variable is always not defined
#self.ids.list_one.add_widget(OneLineListItem(text='List Item 1'))
#root.ids.list_one.add_widget(OneLineListItem(text='List Item 1'))
#ids.list_one.add_widget(OneLineListItem(text='List Item 1'))
# This function works when called from a button
def button_push(self):
for i in range (20):
self.ids.list_one.add_widget(OneLineListItem(text=f'List Item {i}'))
class SecondWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
class MultiscreenApp(MDApp):
def build(self):
return Builder.load_file('Multiscreen.kv')
if __name__ == '__main__':
MultiscreenApp().run()
答案 0 :(得分:1)
class FirstWindow(Screen):
def on_enter(self, *args):
"""Event fired when the screen is displayed: the entering animation is
complete."""
def on_enter(interval):
for i in range (20):
self.ids.list_one.add_widget(OneLineListItem(text=f'List Item {i}'))
Clock.schedule_once(on_enter)
答案 1 :(得分:1)
您可以在__init___
中添加Clock.schedule_once
方法来触发列表的创建。修改后的代码如下。我没有更改其余代码,只是添加了两个功能来显示自动创建列表。
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.uix.list import OneLineListItem
from kivy.clock import Clock
class FirstWindow(Screen):
print('This prints automatically when App launches')
def __init__(self, **kwargs):
super().__init__(**kwargs)
Clock.schedule_once(self.create_list)
def create_list(self, *args):
for i in range (20):
self.ids.list_one.add_widget(OneLineListItem(text=f'List Item {i}'))
# But adding widgets doesn't happen automatically
# I tried variations but the variable is always not defined
#self.ids.list_one.add_widget(OneLineListItem(text='List Item 1'))
#root.ids.list_one.add_widget(OneLineListItem(text='List Item 1'))
#ids.list_one.add_widget(OneLineListItem(text='List Item 1'))
# This function works when called from a button
def button_push(self):
for i in range (20):
self.ids.list_one.add_widget(OneLineListItem(text=f'List Item {i}'))
class SecondWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
class MultiscreenApp(MDApp):
def build(self):
return Builder.load_file('Multiscreen.kv')
if __name__ == '__main__':
MultiscreenApp().run()