I developed a simple app with Flet Python. The app contains some controls such as text and buttons organized in rows and columns. Here is my code:
import flet as ft
def main(page: ft.Page):
def Next_Image(e):
print(page.controls)
# CONTROLS DESIGN
cont = ft.Container(bgcolor=ft.colors.AMBER,
border=ft.border.all(3, ft.colors.RED),
width=250,
height=600,
)
button_previous_img = ft.IconButton(icon=ft.icons.ARROW_CIRCLE_LEFT, tooltip='Previous Image')
button_next_img = ft.IconButton(icon=ft.icons.ARROW_CIRCLE_RIGHT, tooltip='Next Image', on_click=Next_Image)
text_num_img = ft.Text(value="DOC")
# ADD CONTROLS TO THE PAGE
page.add(
ft.Column(
[
cont,
ft.Row(
[
button_previous_img,
text_num_img,
button_next_img
],
alignment=ft.MainAxisAlignment.CENTER,
)
],
horizontal_alignment = ft.CrossAxisAlignment.CENTER,
)
)
page.update()
ft.app(target=main)
I would like to retrieve the whole tree of children controls added to the page pressing a button. I'm able to display only the outmost control, specifically the column. Moreover, I would like to access to a control, let's say the container 'cont' inside the button event 'Next_Image()'. Is there a way to access to him with the name variable or with its index within the controls collection? Such as:
cont = page.controls["cont"] # with the variable name
cont = page.controls["4"] # with the variable index (assuming it's 4)
If you want tree of controls you can use this:
def get_tree(controls, indent=""):
indent = indent + "\t"
for con in controls:
print(f"{indent}{con._get_control_name()}")
if hasattr(con, 'controls'):
if len(con.controls) > 0:
get_tree(con.controls, indent)
elif hasattr(con, 'content'):
if hasattr(con.content, 'controls'):
if len(con.content.controls) > 0:
get_tree(con.content.controls, indent)
else:
continue
get_tree(page.controls)
Code goes thru controls
print them and print their children and go deeper etc.
For getting control by index you can you use
cont = page.controls[0].controls[0]
if you want get cont
.
By page.controls[0]
you get in to ft.Column
and then you want children of ft.Column
so you use page.controls[0].controls[0]
and you have what you want