簡體   English   中英

如何訪問 Kivy 中的 ID?

[英]How do I access ids in Kivy?

我是 Kivy 的初學者(盡管不是 Python),我正在努力將 id 從 kv 字符串獲取到我的主代碼中。 我有以下內容,但“打印”語句告訴我沒有 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM