【问题标题】:add_widget and remove_widget for a class in kivykivy 中的一个类的 add_widget 和 remove_widget
【发布时间】:2021-11-10 17:11:44
【问题描述】:

我是 Kivy 的新手,很抱歉在帖子中问了 2 个问题..

首先,为什么remove_widget() 不起作用?它说AttributeError: 'MyCard' object has no attribute 'remove_card',但我试图将它们放在其他类中,它仍然不起作用。

第二,为什么我的小部件仍然有“焦点行为”,即使我放了一张颜色几乎不透明的卡片,我的按钮仍然可以点击

这是我的 main.py 文件

class MyCard(Screen):
    pass

class HomeScreen(Screen):
    def add_card(self):
        self.add_widget(MyCard())
    def remove_card(self):
        self.remove_widget(MyCard(name='cardd'))

class AVCard(Screen):
    pass

class ScreenApp(MDApp):
    def build(self):
        def build(self):
    sm = ScreenManager(transition=FadeTransition(duration=0.2))
    sm.add_widget(HomeScreen(name='home'))
    sm.add_widget(AVCard(name='av'))
    return sm

这是我的 home.kv 文件(AVCard 类有自己的 .kv 文件)

<HomeScreen>:
    name: 'home'
    MDIconButton:
        on_release: root.add_card()
        ...

<MyCard>:
    name: 'cardd'
    MDCard: #-> I put this card is to not allow user click on widgets behind it but it does not work
        md_bg_color: 0, 0, 0, .3
        ...
    MDCard: #-> Thís card is like a window which includes small widgets in it
        ...
        Screen:
            MDIconButton: #-> The close button
                icon: "close-circle"
                ...
                on_release:
                    root.remove_card()

非常感谢。

【问题讨论】:

    标签: python kivy kivy-language kivymd


    【解决方案1】:

    在您的kv 中,root.remove_card() 试图引用rootremove_card() 方法。在这种情况下,root 指的是它出现的规则的根,即MyCard。这就是您看到错误消息的原因,remove_card() 不在 MyCard 对象中。解决方法是使用对包含remove_card() 方法的正确对象的引用,如下所示:

    <MyCard>:
        MDCard: #-> I put this card is to not allow user click on widgets behind it but it does not work
            md_bg_color: 0, 0, 0, .3
        MDCard: #-> Thís card is like a window which includes small widgets in it
            Screen:
                MDIconButton: #-> The close button
                    icon: "close-circle"
                    on_release:
                        app.root.get_screen('home').remove_card(root)
    

    注意app.root.get_screen('home').remove_card(root)的使用,这会获得对HomeScreen对象的引用(假设使用的namehome),并用root调用它的remove_card()方法(MyCard实例)作为参数。

    那么,在HomeScreen类中,remove_card()方法可以是:

    def remove_card(self, card):
        self.remove_widget(card)
    

    【讨论】:

    • 我的HomeScreen id 是home,我像你一样使用app.root.get_screen('home').remove_card(),但是当我点击关闭按钮时,它并没有消失..
    • 你的Screens 应该都有一个name 属性(这里不讨论ids)。
    • 还是不行..对不起我的愚蠢,先生..更新了我的代码,你能看一下吗?..非常感谢。
    • 查看更新的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多