Dynamic Select Widgets: when to use set_options? #4935
-
Hi, in my TUI I like to dynamically add (and remove) widgets, even select widgets. For some reason I can't give the options to the select widget during construction but have to do it later1. So I try to use It simply shows three buttons. Two of them will dynamically add an input widget and a select widget, the third will manipulate these widgets. The input widget is just to demonstrate what I would like to do even with the select widget. The two event handlers for the first two buttons should...
Step 3 works for the input widget, but not for the select widget. The error message is Commanding out lines 54/55 will allow to use the third button (of cource after clicking the first and second). It will trigger the same code (line 64) which didn't work above, but here it works and set the select options. from textual import on
from textual.app import App
from textual.containers import Vertical, Grid
from textual.widgets import Button, Input, Select
class Main(App):
CSS = """
Grid {
grid-size: 2;
}
"""
def compose(self):
# make and remember a container for dynamically build widgets
self.gridContainer = Grid()
with Vertical():
# Two buttons to dynamically insert widgets
yield Button('Insert Input', id='insertInput')
yield Button('Insert Select', id='insertSelect')
# A button to manipulate the dynamically inserted widgets
yield Button('Set options/value',id='setOptions')
# At last the container (Grid) for dynamically build widgets
yield self.gridContainer
@on(Button.Pressed, '#insertInput')
def iI(self):
# build input widget
Wdg = Input(id='dynInput')
# mount it
self.gridContainer.mount(Wdg)
# manipulate it
Wdg.value = 'Hello World'
# works just once because of the id
self.query_one('#insertInput').disabled = True
@on(Button.Pressed, '#insertSelect')
def iS(self):
# build select widget
Wdg = Select((), id='dynSelect')
# mount it
self.gridContainer.mount(Wdg)
# try to manipulate it - doesn't work
options = (('One', '1'), ('Two', '2'), ('Three', '3'))
# Wdg.set_options(options)
self.query_one('#dynSelect').set_options(options)
# works just once because of the id
self.query_one('#insertSelect').disabled = True
@on(Button.Pressed, '#setOptions')
def setOpt(self):
options = (('Ten', '10'), ('Eleven', '11'), ('Twelve', '12'))
# here the same code which didn't work at line 55:
self.query_one('#dynSelect').set_options(options)
self.query_one('#dynInput').value = 'Hello again'
if __name__ == "__main__":
app = Main()
app.run() Where I'm wrong in my construction? Any ideas how to make it work? Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The problem is that the mount process has not yet completed, so you will need to await the result of |
Beta Was this translation helpful? Give feedback.
The problem is that the mount process has not yet completed, so you will need to await the result of
mount
. See https://textual.textualize.io/guide/app/#awaiting-mount