Search code examples
pythonuser-interfacedirectoryflet

How to add buttons dynamically with flet (Python)?


I'm trying to add a new button to choose directory after choosing the perv direcotry (in order to choose multiple directories).

This select-directory button needs to appand everytime after I choose directory. How can I do that?

Edit: Attaching my code here:

# Method to create a file picker
self.images_dir = FileChooseRow(
            "Images Folder",
            MetaFileType.DIRECTORY,
            pick_files_dialogs[0],
            fn_validate_submit,
)

def button_clicked(e):
            self.add_images_dir.data += 1
            self.row = ft.Row()
            self.row.update()

# create button to add another file picker on screen on run time
self.add_images_dir = ft.IconButton(
            icon="add", tooltip="Add", height=40, on_click=button_clicked, data=0
)
self.row = ft.Row()

I need something like this: https://jsfiddle.net/SP8de/


Solution

  • I guess this is what you want:

    • Press a "Chose directory button" (main button) to make another button appear.
    • Press the other button to chose a directory

    I would firstly make a variable to store the added buttons and a row whose controls are set to the array. Then you can add your main button into it. Eg.

    main_btn = ft.ElevatedButton(text="Chose directory")
    added_btns = [main_btn]
    r = ft.Row(added_btns)
    page.add(r)
    

    Next, make the callback for the main button

    def add_button(e: ft.ControlEvent):
    
        def dir_btn_pressed(e: ft.ControlEvent):
            picker.ask_directory(initial_directory="...")
    
        new_btn = ft.TextButton(text="Chose Directory")
        new_btn.on_click=dir_btn_pressed
        added_buttons.append(new_btn)
        page.update()
    
    main_btn.onclick = add_button
    

    Now implement the directory picker:

    def dir_picked(e: ft.FilePickerResultEvent):
        print(f"Picked {e.path}")
    
    picker = ft.FilePicker(on_result=dir_picked)
    
    

    You may have to fix the odd typo :)