如何在Kivy中按ID正确链接按钮?

时间:2019-05-20 08:29:17

标签: python python-3.x kivy

我想在boxlayout中添加按钮,但是我的代码中存在一些问题。当我单击添加按钮或删除按钮时,我收到AttributeError消息。 感谢您的帮助。

我的python代码:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen, ScreenManager


class MainScreen(Screen):
    pass

class SecondScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass


class TestApp(App):
    def build(self):
        self.title = 'Hello'

    def add_more(self):
        print('test')
        addbutton = self.root.ids.abc
        addbutton.add_widget(Button(text='hello'))

    def remove(self):
        print('test')
        if len(self.root.ids.abc.children) > 0:
            self.root.ids.abc.remove_widget(self.root.ids.abc.children[0])



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

我的kv代码:

#: import SwapTransition kivy.uix.screenmanager.SwapTransition

ScreenManagement:
    transition: SwapTransition()
    MainScreen:
    SecondScreen:



<MainScreen>:
    BoxLayout:
        id:aaa
        Button:
            text: 'Add'
            on_press: app.add_more()

        Button:
            text:'Remove'
            on_press: app.remove()
        BoxLayout:
            id:abc


<SecondScreen>:

AttributeError:“超级”对象没有属性“ getattr

1 个答案:

答案 0 :(得分:2)

问题-AttributeError

     addbutton = self.root.ids.abc
   File "kivy/properties.pyx", line 843, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

根本原因

id: abc中没有ScreenManager

解决方案

解决方案有两个选择。

选项1-使用get_screen()

在此选项中,我们使用get_screen()函数检索实例化的对象MainScreen:,以便我们可以访问其方法或属性,例如id: abc。我们将进行以下增强:

kv文件:

  • 我们name屏幕name: 'MainScreen'name: 'SecondScreen'分别用于实例化对象MainScreen:SecondScreen:

摘要-kv文件

ScreenManagement:
    transition: SwapTransition()
    MainScreen:
        name: 'MainScreen'
    SecondScreen:
        name: 'SecondScreen'

Py文件

摘要-Py文件

def add_more(self):
    print('test')
    addbutton = self.root.get_screen('MainScreen').ids.abc
    addbutton.add_widget(Button(text='hello'))

def remove(self):
    print('test')
    container = self.root.get_screen('MainScreen').ids.abc
    if len(container.children) > 0:
        container.remove_widget(container.children[0])

选项2-使用ID:主屏幕

在此选项中,我们将id: mainscreen添加到实例化对象MainScreen:中,并使用ids.mainscreen访问其方法或属性,例如id: abc。我们将进行以下增强:

kv文件:

  • id: mainscreen添加到实例化对象MainScreen:

摘要-kv文件

ScreenManagement:
    transition: SwapTransition()
    MainScreen:
        id: mainscreen
    SecondScreen:

Py文件

  • self.root.ids.abc替换为self.root.ids.mainscreen.ids.abc

摘要-Py文件

def add_more(self):
    print('test')
    addbutton = self.root.ids.mainscreen.ids.abc
    addbutton.add_widget(Button(text='hello'))

def remove(self):
    print('test')
    container = self.root.ids.mainscreen.ids.abc
    if len(container.children) > 0:
        container.remove_widget(container.children[0])