我有这个代码。
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
class Temp(BoxLayout):
def __init__(self, iid):
BoxLayout.__init__(self)
self.id = str(iid)
def remove_content(self, iid):
#How me need use remove_widget() function?
#self.ids['tmp'].remove_widget(?)
class ScreenApp(BoxLayout):
def __init__(self):
BoxLayout.__init__(self)
self.idsum = 0
self.idsum+=1
self.ids['contents'].add_widget(Temp(iid = self.idsum))
self.idsum+=1
self.ids['contents'].add_widget(Temp(iid = self.idsum))
def add_content(self):
self.idsum+=1
self.ids['contents'].add_widget(Temp(iid = self.idsum))
class MainApp(App):
def build(self):
return ScreenApp()
if __name__ == "__main__":
MainApp().run()
还有这个
<Temp@BoxLayout>
id: tmp
Button:
id: idti
text: "-"
on_press: root.remove_content(id)
Label:
id: idlbl
text: "Temp"
<ScreenApp>:
BoxLayout:
orientation: "vertical"
BoxLayout:
id: contents
orientation: "vertical"
Button:
text: "+"
on_press: root.add_content()
我想单击按钮即可删除小部件,最下面的小部件最不应该留在空白处,而上升到远程小部件TM的位置。先感谢您。 再输入几个字即可删除弹出窗口。
答案 0 :(得分:0)
使用self.ids.contents.remove_widget(instance)
删除对象的实例。有关详细信息,请参阅说明和示例。
<Temp@BoxLayout>
替换动态类<Temp>:
id: tmp
,因为它不需要root.remove_content(id)
替换app.root.remove_content(root)
,因为我们已经将方法移到ScreenApp()类中了,因为那里已经有add_content()
方法了。id
而不是传递root
作为参数,即传递Temp
对象的实例。text: 'Temp'
替换为root.text
以进行可视化。BoxLayout:
<ScreenApp>:
,因为它已经是BoxLayout了,实际上并不需要另一个BoxLayout,即嵌套的BoxLayouts。text
添加为类Temp()
的构造方法的参数。self.text = text
进行分配text='Temp' + str(self.idsum)
对象时添加了Temp
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class Temp(BoxLayout):
def __init__(self, iid, text, **kwargs):
super(Temp, self).__init__(**kwargs)
self.id = str(iid)
self.text = text
class ScreenApp(BoxLayout):
def __init__(self):
BoxLayout.__init__(self)
self.idsum = 0
self.idsum += 1
self.ids['contents'].add_widget(Temp(iid=self.idsum, text='Temp' + str(self.idsum)))
self.idsum += 1
self.ids['contents'].add_widget(Temp(iid=self.idsum, text='Temp' + str(self.idsum)))
def add_content(self):
self.idsum+=1
self.ids['contents'].add_widget(Temp(iid=self.idsum, text='Temp' + str(self.idsum)))
def remove_content(self, instance):
self.ids.contents.remove_widget(instance)
class MainApp(App):
def build(self):
return ScreenApp()
if __name__ == "__main__":
MainApp().run()
#:kivy 1.11.0
<Temp>:
text: 'Temp'
Button:
id: idti
text: "-"
on_press: app.root.remove_content(root)
Label:
id: idlbl
text: root.text
<ScreenApp>:
orientation: "vertical"
BoxLayout:
id: contents
orientation: "vertical"
Button:
text: "+"
on_press: root.add_content()