无法在Kivy中引用widget id

2024-09-28 17:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

对Kivy来说非常陌生,并且尝试动态地添加小部件,但是尽管我遵循了所有的示例,我还是无法使用我的。在

我的.kv文件是。。。在

ScreenManager:
    MainScreen:
    LoginScreen:

<MainScreen>:
   name: 'MainScreen'
   id: ms

   BoxLayout:
        id: rc_display
        orientation: "vertical"
        padding: 10
        spacing: 10

        Label:
            id: ms_label1
            text: 'Oh Hell Yeah'

<LoginScreen>:
    name: 'LoginScreen'
    id: ls

    Button:
        on_release: app.root.current
        text: 'Click to Login'
        font_size: 20

我的python代码是。。。在

^{pr2}$

当我运行以上我得到以下错误。。。在

File "*pathtoFile*/StagePlanning.py", line 12, in on_pre_enter
 show_view = self.ids.rc_display
File "kivy\properties.pyx", line 839, in kivy.properties.ObservableDict.__getattr__ (kivy\properties.c:12654)
AttributeError: 'super' object has no attribute '__getattr__'

如果我将这些小部件直接添加到屏幕对象中,它们会显示,但会相互叠加。只有当我尝试引用id时才会出错。在

我甚至在控制台上打印了id的列表,它们如预期的那样在那里。在


Tags: textnameinidon部件displayline
1条回答
网友
1楼 · 发布于 2024-09-28 17:25:47

问题是由于on_pre_enter事件是在添加BoxLayout之前完成的,因此它不存在,一个可能的解决方案是使用Clock

class MainScreen(Screen):
    def __init__(self, *args, **kwargs):
        Screen.__init__(self, *args, **kwargs)
        Clock.schedule_once(self.finished_init)

    def finished_init(self, *args):
        show_view = self.ids.rc_display # error here
        show_view.clear_widgets()
        buttons = BoxLayout(orientation = 'vertical')
        pr = requests.get('http://127.0.0.1:5000/stageplanning/api/v1.0/shows')
        for show in pr.json():
            buttons.add_widget(Button(text = show['show_title']))

        show_view.add_widget(buttons) 

另一个选项是在BoxLayout构造函数中定义它:

*.py

^{pr2}$

*.kv

ScreenManager:
    MainScreen:
    LoginScreen:

<MainScreen>:
    name: 'MainScreen'
    id: ms

    MainBoxLayout:
        id: rc_display
        orientation: "vertical"
        padding: 10
        spacing: 10

<LoginScreen>:
    name: 'LoginScreen'
    id: ls

    Button:
        on_release: app.root.current
        text: 'Click to Login'
        font_size: 20

相关问题 更多 >