首页 > 解决方案 > 如何让按钮自行删除?

问题描述

因此,在 Kivy 中,您通常删除按钮的方式是访问它们的 id 或名称或其他内容。有什么方法可以访问被按下的按钮的信息,以便在按下时它可以自行删除?假设您有很多按钮并且您不知道 id 或者您有 100 个按钮并且需要很长时间?

标签: pythonkivy

解决方案


删除小部件

使用remove_widget()从子列表中删除一个小部件。

    self.parent.remove_widget(self)

删除所有小部件/按钮

使用clear_widgets()从小部件中删除所有子/按钮

        self.parent.clear_widgets()

许多按钮

实现一个继承 的类Button,以及一个on_touch_down带有collide_point()检查触摸与我们的小部件碰撞的函数的方法。

Kivy » 触摸事件基础

默认情况下,触摸事件被调度到所有当前显示的小部件。这意味着小部件接收触摸事件,无论它是否发生在其物理区域内。

...

为了提供最大的灵活性,Kivy 将事件分派给所有小部件,并让它们决定如何对它们做出反应。如果您只想响应小部件内的触摸事件,您只需检查:

def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
        # The touch has occurred inside the widgets area. Do stuff!
        pass

片段

class CustomButton(Button):

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print(f"\nCustomButton.on_touch_down: text={self.text}")
            self.parent.remove_widget(self)    # remove a widget / button
            # self.parent.clear_widgets()    # remove all children/ buttons
            return True    # consumed on_touch_down & stop propagation / bubbling
        return super(CustomButton, self).on_touch_down(touch)

例子

主文件

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder


Builder.load_string("""
<Demo>:
    cols: 10
""")


class CustomButton(Button):

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print(f"\nCustomButton.on_touch_down: text={self.text}")
            self.parent.remove_widget(self)    # remove a widget / button
            # self.parent.clear_widgets()    # remove all children / buttons
            return True    # consumed on_touch_down & stop propagation / bubbling
        return super(CustomButton, self).on_touch_down(touch)


class Demo(GridLayout):

    def __init__(self, **kwargs):
        super(Demo, self).__init__(**kwargs)
        self.create_buttons()

    def create_buttons(self):
        for i in range(100):
            self.add_widget(CustomButton(id="Button" + str(i), text="Button"+str(i)))


class TestApp(App):

    def build(self):
        return Demo()


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

输出

应用启动 Button0 - 已删除 按钮 51 和 30 - 已删除


推荐阅读