Search code examples
python-3.xmacosbuttononclickflet

In python3-flet script, how to remove a button after click?


I would like to remove a button when it's clicked. Following my Python3-Flet script:

import flet as fl
def main(page:fl.Page):
    def remove(e):
        pass #what could i do for remove the button?
    page.add(fl.ElevatedButton('REMOVE ME',on_click=remove))
    page.update()
fl.app(target=main)

Solution

  • You can use e.control to remove your element. It helps to you to remove this button.

    import flet as fl
    def main(page:fl.Page):
        def remove(e):
            e.control.page.remove(e.control)
        remove_button = fl.ElevatedButton('REMOVE ME',on_click=remove)
        page.add(remove_button)
        page.update()
    fl.app(target=main)
    

    If you want to remove different element u can use

    import flet as fl
    
    def main(page: fl.Page):
    
        def remove(e):
            e.control.page.controls.remove(other_button)
            e.control.page.update()
        remove_button = fl.ElevatedButton('REMOVE ME', on_click=remove)
        other_button = fl.ElevatedButton("REMOVE THIS")
        page.add(remove_button, other_button)
        page.update()
    
    fl.app(target=main)