我如何访问 Kivy 中的 ID?

How do I access ids in Kivy?

我是 Kivy 的初学者(虽然不是 Python),我正在努力将 id 从 kv 字符串获取到我的主代码中。我有以下内容,但 'print' 语句告诉我没有 ID。应用程序本身运行没有错误。

import kivy
kivy.require('2.1.0')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.image import Image

kvString = """
MainScreen:
  id: maincontainer
  cols: 1
  thumbnails: thumbnails.__self__
  GridLayout:
    id: thumbnails
    cols: 3
    rows: 3
    Image:
      source: "test.png"
"""

class MainScreen(GridLayout):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        # This prints 0
        print("Ids: {}".format(len(self.ids.items())))

class ExampleApp(App):
    def build(self):
        root = Builder.load_string(kvString)
        return root
        
if __name__ == "__main__":
    ExampleApp().run()

当我 运行 你的代码时,我收到了一个严重警告,指出没有屏幕,因此应用程序将终止。一旦我将 MainScreen 切换到屏幕,它就完美地运行了。这是代码:

.py

import kivy
kivy.require('2.1.0')

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.uix.image import Image

sm = ScreenManager()

#I removed some unnecessary code such as the cols, thumbnail, etc.
kvString = """
<MainScreen>
  GridLayout:
    id: thumbnails
    cols: 3
    rows: 3
    Image:
      source: "test.png"
"""
#NEEDS TO INHERIT SCREEN
class MainScreen(Screen):
    def __init__(self, **kwargs):
        super(MainScreen, self).__init__(**kwargs)
        # This now prints 1
        print(f'There are {len(self.ids.items())} id(s)')

class ExampleApp(App):
    def build(self):
        root = Builder.load_string(kvString)
        #Adds the screen
        sm.add_widget(MainScreen(name='screen'))
        return sm

if __name__ == "__main__":
    ExampleApp().run()