How to delete child widgets? #5234
-
Hello, I want to add a sub-widget to the widget when I click the button, but I want to initialize it every time I add it. At this time, I'm curious how to properly delete a widget. In the example below, right-rich should not be removed and only the static added as a child should be deleted. import random
from textual import on
from textual.app import App, ComposeResult
from textual.containers import VerticalScroll, Container
from textual.widgets import Header, Footer, Button, Static
from textual.reactive import reactive
class Test(App):
def compose(self) -> ComposeResult:
yield Header(id="header")
yield Footer()
yield Button(f"Add", id="btn_add", variant="primary")
with Container(id="main-grid"):
with VerticalScroll(id="right-rich"):
pass
@on(Button.Pressed, "#btn_add")
def add_scope(self, event: Button.Pressed):
right_rich = self.query_one("#right-rich")
while right_rich.children:
right_rich.remove(right_rich.children[-1])
num_widgets = random.randint(1, 5)
for i in range(num_widgets):
new_widget = Static(f"Widget {i+1}")
right_rich.mount(new_widget)
if __name__ == "__main__":
Test().run() |
Beta Was this translation helpful? Give feedback.
Answered by
YoonSungHyun-Git
Nov 14, 2024
Replies: 1 comment
-
This is an advisory answer. import random
from textual import on
from textual.app import App, ComposeResult
from textual.containers import VerticalScroll, Container
from textual.widgets import Header, Footer, Button, Static
from textual.reactive import reactive
class Test(App):
def compose(self) -> ComposeResult:
yield Header(id="header")
yield Footer()
yield Button(f"Add", id="btn_add", variant="primary")
with Container(id="main-grid"):
with VerticalScroll(id="right-rich"):
pass
@on(Button.Pressed, "#btn_add")
async def add_scope(self, event: Button.Pressed):
right_rich = self.query_one("#right-rich")
await right_rich.remove_children(selector='*')
num_widgets = random.randint(1, 5)
for i in range(num_widgets):
new_widget = Static(f"Widget {i+1}")
right_rich.mount(new_widget)
if __name__ == "__main__":
Test().run() |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
YoonSungHyun-Git
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is an advisory answer.
remove_children(selector='*') returns awaitable, so use await.