-
QuestionI've got a simple app where I've got a background image, then on top I have a control that should execute some code when clicked. I arranged these as a Stack. But when I run this, I find that the on_click event for the control on top gets called when you click anywhere in the app, not just on the control in the foreground. How do I isolate the on_click event? Code sample# demo flet on_click issue
import flet as ft
import flet.canvas as cv
import os
def click(e):
print('here click')
def main(page: ft.Page):
brd = ft.Image('bgboard_empty.png', width=1000, height=500, fit=ft.ImageFit.FILL)
# brd = ft.Container(cv.Canvas([cv.Rect(width=1000, height=500, paint=ft.Paint(style=ft.PaintingStyle.FILL, color=ft.colors.WHITE))]))
gd = ft.GestureDetector(on_tap=click)
canvas = cv.Canvas([cv.Rect(x=600, y=235, width=30, height=30, paint=ft.Paint(style=ft.PaintingStyle.FILL, color=ft.colors.GREY))], content=gd)
cont = ft.Stack(controls=[
brd,
canvas
], width=1000, height=500)
page.add(ft.Row([cont]))
ft.app(target=main, view=ft.AppView.FLET_APP, assets_dir=os.getcwd()) Error messageNo error message - but if you click anywhere in the app - not just on the little grey box that defines the on_click action - it'll still call the on_click function. ------------------------------------------------------
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Haven't tried your code, but have a suggestion: instead wrap your |
Beta Was this translation helpful? Give feedback.
-
The trick was wrapping the Canvas in a Container, and being careful to specify the dimensions of the container to limit the scope of the click event. Here's the code that works: import flet as ft
import flet.canvas as cv
import os
def click(e):
print('here click')
def main(page: ft.Page):
brd = ft.Image('bgboard_empty.png', width=1000, height=500, fit=ft.ImageFit.FILL)
gd = ft.GestureDetector(on_tap=click)
canvas_container = ft.Container(
width=30,
height=30,
left=600,
top=235,
content=cv.Canvas(
[cv.Rect(x=0, y=0, width=30, height=30, paint=ft.Paint(style=ft.PaintingStyle.FILL, color=ft.colors.GREY))],
content=gd
)
)
cont = ft.Stack(controls=[
brd,
canvas_container # Add the container instead of the raw canvas
], width=1000, height=500)
page.add(ft.Row([cont]))
ft.app(target=main, view=ft.AppView.FLET_APP, assets_dir=os.getcwd()) |
Beta Was this translation helpful? Give feedback.
The trick was wrapping the Canvas in a Container, and being careful to specify the dimensions of the container to limit the scope of the click event. Here's the code that works: