在Kivy中动态添加按钮时出错

问题描述

为了使我的生活更轻松一些,我创建了一个仪表板,可以在该仪表板上为多个客户进行操作。每个客户端都有一个包含每个客户端配置文件文件夹,用于动态构建页面的其余部分。

我现在坚持第一步,那就是为我拥有的每个客户创建一个按钮。

   File "gui.py",line 25,in on_enter
     self.ids.clients.add_widget(clientbutton)
   File "kivy/properties.pyx",line 863,in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

gui.py:

import kivy
import os
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.properties import ObjectProperty
from kivy.uix.button import Button
from kivy.clock import Clock

import subprocess

class ClientListwindow(Screen):   

    def on_enter(self,*args):
        dirs = next(os.walk('clients'))[1]

        for dir in dirs:
            print(dir)
            clientbutton = Button(text=dir)
            # clientbutton.bind(on_pressed=lambda *args: self.pressed('cltbtn',dir,*args))
            self.ids.clients.add_widget(clientbutton)

    def pressed(self,instance,*args):
        print("test")


class ClientGrid(Screen):  
    pass

class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("gui.kv")
sm = WindowManager()

class GuiApp(App):
    def build(self):
        return kv

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

gui.kv

WindowManager:
    ClientListwindow:
    ClientGrid:

<ClientListwindow>:
    name: "clientlist"

    GridLayout:
        cols:2
        size: root.width,root.height

        GridLayout:
            cols:1

            Label:
                text: "Clients:"
                size_hint: 1,0.1

            GridLayout:
                id: clients
                cols:2
                size_hint: 1,0.9


<ClientGrid>:
    name: "client"
    

当我添加print(self.ids)时,似乎没有找到ID。这些什么时候装满?

解决方法

文档没有明确定义ids何时可用,但是如果您从以下方法更改了方法定义:

def on_enter(self,*args):

def on_kv_post(self,base_widget):

它将起作用。在应用on_kv_post()规则之后,将调用kv方法。这还有一个优势,on_kv_post()方法仅被调用一次,而on_enter()方法将在每次ClientListWindow显示时被调用。