python - 如何让按钮自行删除?
问题描述
因此,在 Kivy 中,您通常删除按钮的方式是访问它们的 id 或名称或其他内容。有什么方法可以访问被按下的按钮的信息,以便在按下时它可以自行删除?假设您有很多按钮并且您不知道 id 或者您有 100 个按钮并且需要很长时间?
解决方案
删除小部件
使用remove_widget()从子列表中删除一个小部件。
self.parent.remove_widget(self)
删除所有小部件/按钮
使用clear_widgets()从小部件中删除所有子/按钮
self.parent.clear_widgets()
许多按钮
实现一个继承 的类Button
,以及一个on_touch_down
带有collide_point()
检查触摸与我们的小部件碰撞的函数的方法。
默认情况下,触摸事件被调度到所有当前显示的小部件。这意味着小部件接收触摸事件,无论它是否发生在其物理区域内。
...
为了提供最大的灵活性,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()
输出
推荐阅读
- marklogic - 使用oxyXML编写可以搜索marklogic中所有文档的xquery
- java - 为什么找不到打开的文件,因为文件在那里
- centos7 - 服务器中找不到文件,但已上传
- java - Java - XML 生成 - 空文件
- azure - AcquireTokenAsync:返回什么样的令牌?
- r - ggplot图例(geom_point)中的空白条目?
- google-apps-script - 已部署的编辑器 Google 表格插件未显示给域成员
- mysql - 无法从 Lumen 连接到亚马逊 AWS RDS Mysql
- wolfram-mathematica - Wolfram Mathematica Solve command for a nonlinear system of equations
- kotlin - 在 Kotlin 中通过委托访问委托接收器