prompt-toolkit / python-prompt-toolkit

Library for building powerful interactive command line applications in Python
https://python-prompt-toolkit.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
9.1k stars 717 forks source link

Dynamically Update RadioList #1795

Open stripuramallu3 opened 8 months ago

stripuramallu3 commented 8 months ago

I was wondering if its possible to dynamically update the items in a RadioList.

I've figured out how to update the data inside of a TextArea, and would like to do something similar with the RadioList:

def handle_enter():
    new_value = self.radios.values[self.radios._selected_index][0]
    self.radios.current_value = new_value
    self.text_area.text = "new text"
self.radios._handle_enter = handle_enter

I've tried updating the RadioList's values and current_values but that didn't work:

def update_data(self, new_threads):
  radio_values = [(thread["id"], thread["messages"][0]["subject"]) for thread in threads]
  self.radios.values = radio_values
  self.radios.current_values = radio_values
  self.radios.current_value = radio_values[0][0]
  self.text_area.text = "new text"
  self.app.invalidate()
joouha commented 7 months ago

Hi,

You should be able to update the values attribute on your RadioList instance, as shown in the example below. The radio options change when the c key is pressed.

from prompt_toolkit.application import Application, get_app
from prompt_toolkit.layout.layout import Layout
from prompt_toolkit.widgets import RadioList
from prompt_toolkit.key_binding import KeyBindings

radios = RadioList([(0, "a"), (1, "b"), (2, "c")])

kb = KeyBindings()

@kb.add("q")
def _quit(event):
    get_app().exit()

@kb.add("c")
def _change(even):
    radios.values = [(0, "x"), (1, "y"), (2, "z")]

Application(layout=Layout(radios), key_bindings=kb).run()

You could access the RadioList's key-bindings with radios.control.key_bindings and add they key-binding there.