我有一个删除按钮,可以从另一个页面删除小部件。但是,该按钮实际上并未删除小部件。该按钮还应该删除附加到小部件的json对象,但是它也不会这样做。
代码:
onMessageRender()
# displays the streak that was clicked on in screen two
def display_streak(self, obj):
self.third_screen()
name = obj.id
bottle = self.root.get_screen("three")
can = self.root.get_screen('two')
bottle.ids.del_space.add_widget(Button(id=name, text="Delete", size=(60,25), size_hint=(None,None),
font_size=18, on_press=self.del_button)) # fix later
我试图将def del_button(self, obj):
bottle = self.root.get_screen("two")
can = self.root.get_screen('three')
name = obj.id
with open("streak.json", "r+") as f:
data = json.load(f)
for child in self.root.screen_two.ids.streak_zone.children:
if child.text == name:
print("delete")
bottle.screen_two.ids.streak_zone.remove_widget(child)
for i in xrange(len(data)):
if data[i] == name:
data.pop(i)
break
open("streak.json", "w").write(json.dump(data, sort_keys=True, indent=4))
中的Button的ID与del_space
中的小部件内部的文本进行比较,以便删除,但是由于某些原因,这是行不通的。我什至从streak_zone
传递了obj,但它仍然不起作用,怎么来的?
EDIT
on_press=self.del_button
中的 obj
是从将函数绑定到按钮小部件的条件传递的:
display_streak()
EDIT
我不确定,但是我认为问题可能出在我的奇异代码上:
elif delay > time.time() > self.honey: # on time (green)
child.background_normal = ''
child.background_color = [0, 1, 0, .95]
child.unbind(on_press=self.early_click)
child.bind(on_press=self.add_score)
child.bind(on_press=self.display_streak)
child.bind(on_press=self.draw_streak)
进入第二页时,<ScreenTwo>
id: screen_two
name: "two"
on_leave: app.restart()
on_enter: app.display_btn()
ScrollView:
GridLayout:
cols: 2
rows: 1
ScrollView:
BoxLayout:
id: streak_zone
orientation: 'vertical'
height: self.minimum_height
被激活
Python:
display_btn
如果这是不删除按钮的原因,那么我该如何解决这个问题?
答案 0 :(得分:0)
child.text
替换为child.id
reversed()
的第一个self.root.screen_two.ids.streak_zone.children
开始,将child
添加到children
screen_two
中删除bottle.screen_two.ids.streak_zone.remove_widget(child)
,因为bottle
是对象ScreenTwo
的实例def del_button(self, obj):
bottle = self.root.get_screen("two")
can = self.root.get_screen('three')
name = obj.id
with open("streak.json", "r+") as f:
data = json.load(f)
for child in reversed(bottle.ids.streak_zone.children):
if child.id == name:
print("delete")
bottle.ids.streak_zone.remove_widget(child)
答案 1 :(得分:0)
由于kv文件在离开时删除了小部件,所以我只需要删除与小部件具有相同ID的json元素
def del_button(self, object):
name = object.id
with open("streak.json", "r") as f:
data = json.load(f)
with open("streak.json", "r+") as file:
data = json.load(file)
data.pop(name, None)
file.seek(0)
json.dump(data, file, indent=4)
file.truncate()
self.change_screen()