簡體   English   中英

在 KV 文件中更改 Kivy 類屬性

[英]Changing Kivy class property within KV file

我想更改位於多個位置的切換按鈕的屬性。 當我運行代碼時,我得到AttributeError: 'super' object has no attribute '__getattr__' 我是否必須在 python 文件中創建按鈕才能工作?

from kivy.app import App
from kivy.lang import Builder

KV = Builder.load_string("""

ScreenManager:
    Screen:
        name: 'screen'
        GridLayout:
            cols:1
            rows:3

            TButton:
            TButton:

            Button:
                text:
                    'Reset button'
                on_release:
                    app.root.get_screen('screen').ids.toggle_buttons.state = 'normal'

<TButton@ToggleButton>:
    id: toggle_buttons
    allow_no_selection: True
    text: 'Toggle Button'

""")

class MyApp(App):
    def build(self):
        return KV

if __name__ == '__main__':
    MyApp().run()

當我按下“重置按鈕”時,TButton 的state應該重置為'normal'

首先,您必須了解 id 必須具有本地范圍,並且不應在它之外使用它。 所以toggle_buttons id 應該只在TButton 的實現中使用。

根據您的邏輯,假設您只想通過該 id 重置一個按鈕,如果它們具有相同的 id,我該如何識別該按鈕? 正如我們所見,這是不可能的。

解決方案是實現一個屬性,該屬性存儲按鈕的 id,並通過設置該屬性進行迭代。

ScreenManager:
    buttons: [btn1, btn2] # <---
    Screen:
        name: 'screen'
        GridLayout:
            cols:1
            rows:3
            TButton:
                id: btn1
            TButton:
                id: btn2
            Button:
                text:
                    'Reset button'
                on_release: for btn in root.buttons: btn.state = 'normal'

<TButton@ToggleButton>:
    id: toggle_buttons
    allow_no_selection: True
    text: 'Toggle Button'

暫無
暫無

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

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