So I have been trying to write a kivy program, which first uses another py file to read latin sentences from a file, then dynamically create buttons for each sentence, when one of the buttons is clicked, it should delete itself. I was sucsessfull trying to create buttons dynamically, but I could'nt make them delete themselfs. The problem is if I create a Object property, declare it in kv file and bind it with the id, I can assign a function for on_release. But I want this to happen automatically, and if I have 15 sentences, I dont want to declare the Objectproperty 15 times in the kv file. I have tried creating a list, then creating number of sentences items in it, and making those items a objectproperty. But then I get a error when declaring it in the kv file. Here is my code:
import kivy
from Nils_Programm_verkürzt import lektionstextlesen
from kivy.app import App
from kivy.uix.label import Label, Widget
from kivy.uix.button import Button
from kivy.properties import (
NumericProperty, ReferenceListProperty, ObjectProperty, StringProperty, ListProperty
)
from kivy.lang import Builder
##################
#INPUT FILE:
Inputfile = 'Lektionstext15.txt'
ReturnTuple = []
ReturnTuple = lektionstextlesen(Inputfile)
Satzliste = ReturnTuple[0]
Worterliste = ReturnTuple[1]
kv = """
#:import Button kivy.uix.button.Button
<Testwidget>:
canvas:
Rectangle:
pos: 0, self.center_y
size: self.width, 10
Rectangle:
pos: self.pos
size: self.size
source: 'background.png'"""
add = """
Buttons: Buttons
Button:
id : Buttons[{index}]
text: str(root.Satzliste[{index}])
center_x: root.width / 2
top: root.top - 100 - {num}
font_size: 30
size: self.texture_size
on_release: root.callback({index})
"""
#addf = add.format(num=0)
for i in range(len(Satzliste)):
addf = add.format(index = i, num=(i*50))
kv = f"{kv}{addf}"
#kv = f"{kv}{addf}"
#print(kv)
Builder.load_string(kv)
class Testwidget(Widget):
Satzliste = StringProperty()
Worterliste = StringProperty()
ReturnTuple = []
ReturnTuple = lektionstextlesen(Inputfile)
Satzliste = ReturnTuple[0]
Worterliste = ReturnTuple[1]
Buttons = []
for i in range(len(Satzliste)):
Buttons.append(ObjectProperty(None))
def callback(self, m):
self.remove_widget(self.Buttons[m])
pass
class GuiApp(App):
def build(self):
return Testwidget()
if __name__ == '__main__':
GuiApp().run()