gpt4 book ai didi

python - 如何让按钮自动删除?

转载 作者:行者123 更新时间:2023-12-01 07:51:41 26 4
gpt4 key购买 nike

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

最佳答案

删除小部件

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

    self.parent.remove_widget(self)

删除所有小部件/按钮

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

        self.parent.clear_widgets()

许多按钮

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

Kivy » Touch event basics

By default, touch events are dispatched to all currently displayed widgets. This means widgets receive the touch event whether it occurs within their physical area or not.

...

In order to provide the maximum flexibility, Kivy dispatches the events to all the widgets and lets them decide how to react to them. If you only want to respond to touch events inside the widget, you simply check:

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)

示例

main.py
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()

输出

App Started Button0 - Deleted Buttons 51 and 30 - Deleted

关于python - 如何让按钮自动删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56176459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com