What's the proper way to accept parameters for a custom widget, but still set an id? #3522
-
Example of my custom widget for testing purposes: #!/usr/bin/env python3.11
from textual.app import ComposeResult, App
from textual.widgets import Label, Static
class SayWord(Static):
"""
Simple little widget to say a word
"""
def __init__(self, word: str = "") -> None:
self.word = word
super().__init__()
def compose(self) -> ComposeResult:
yield Label(f"I have to say: {self.word}")
class YeeHawApp(App):
"""
simple little app to say yeehaw
"""
def compose(self) -> ComposeResult:
yield SayWord("yeehaw")
if __name__ == "__main__":
YeeHawApp().run() This works fine, but if I want to style or query the widget, I'm not sure how if there's multiple of that widget on the screen. Example, if I change my class YeeHawApp(App):
"""
simple little app to say yeehaw AND the spice must flow 🤠 + 🪱
"""
CSS = """
#beepboop {
border: solid magenta;
}
"""
def compose(self) -> ComposeResult:
yield SayWord("yeehaw?", id="beepboop")
yield SayWord("The spice must flow", id="ominous")
def on_mount(self) -> None:
self.get_widget_by_id("beepboop").border_title = "don't be a stranger" Rich Traceback
Get widgets by id is super useful, but if I try setting class SayWord(Static):
"""
Simple little widget to say a word
"""
def __init__(self, word: str = "", id: str = "") -> None:
self.word = word
self._id = id
super().__init__()
def compose(self) -> ComposeResult:
yield Label(f"I have to say: {self.word}") Rich Traceback
As always, thank you for developing Textual and Rich, and thank you any help you can provide 🙇 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You will need to pass through the id to the constructor of the base class. Something like this: class SayWord(Static):
"""
Simple little widget to say a word
"""
def __init__(self, word: str = "", id: str = "") -> None:
self.word = word
super().__init__(id=id)
def compose(self) -> ComposeResult:
yield Label(f"I have to say: {self.word}") |
Beta Was this translation helpful? Give feedback.
You will need to pass through the id to the constructor of the base class. Something like this: