I want to know how to remove a specific Rectangle object in Kivy. I create the Rectangle in .py file by pressing a button and I want to the second button could be able to remove that specific Rectangle. My .py code:
import kivy
kivy.require("1.10.1")
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.app import App
from kivy.graphics import RoundedRectangle
class Screen1(Screen):
def create_on_press(self):
with self.canvas:
RoundedRectangle(pos = (770, 1250), size = (400, 400), size_hint = (None, None), source = "Rectangle.jpeg")
def remove_on_press(self):
pass #I don't know what to write there
class Test(App):
def build(self):
Builder.load_file("Test.kv")
sm = ScreenManager(transition = FadeTransition())
sm.add_widget(Screen1(name = "scr1"))
return sm
Test().run()
And the .kv file:
#: kivy 1.10.1
<Screen1>:
id: scr1
orientation: "vertical"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: "Background.png"
Button:
pos: (root.width - 600) / 2, 800
size: 600, 200
text: "Create rectangle"
on_press: scr1.create_on_press()
pos_hint: {'width': 0.5, 'top': 0.8}
size_hint: None, None
Button:
pos: (root.width - 600) / 2, 200
size: 600, 200
text: "Remove rectangle"
on_press: scr1.remove_on_press
pos_hint: {'width': 0.5, 'top': 0.2}
size_hint: None, None
Thanks for any help.
I tried to use self.parent.remove_widget, but it removed the whole Screen1. However, I want to remove only this Rectangle.
One of the various ways can be adding a group
attr. and remove that group later. Since RoundedRectangle
is inherited from class Instruction
, you can set its attr. group
and later use method remove_group
to remove that particular group as follows,
def create_on_press(self):
with self.canvas:
RoundedRectangle(pos = (770, 1250), size = (400, 400), size_hint = (None, None), source = "Rectangle.jpeg", group = u"rect")
def remove_on_press(self):
self.canvas.remove_group(u"rect")
Also an obvious change you need in .kv
,
...
Button:
pos: (root.width - 600) / 2, 200
size: 600, 200
text: "Remove rectangle"
on_press: scr1.remove_on_press() # Call the function.
...