You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Flet开发Python项目:No按钮鼠标悬停移位功能实现求助

解决Flet中"No"按钮鼠标悬停随机移位的问题

问题核心原因

你的代码存在两个关键问题导致按钮无法移位:

  1. 布局容器不支持绝对定位:默认页面采用垂直流式布局,直接修改控件的top和left属性不会生效,必须使用Stack组件承载需要自由定位的控件。
  2. 事件绑定错误:你使用了on_focus和on_click事件,但实现悬停移位需要绑定on_hover事件(鼠标进入/离开控件时触发)。

修改后的完整代码

import random
import flet as ft

def main(janela: ft.Page):
    janela.title = "Teste!"
    janela.theme_mode = ft.ThemeMode.DARK
    janela.vertical_alignment = ft.MainAxisAlignment.CENTER
    janela.horizontal_alignment = ft.CrossAxisAlignment.CENTER

    def fechar():
        janela.window_destroy()

    popup = ft.AlertDialog(
        modal=True,
        title=ft.Text("Close!"),
        content="kkk", 
        actions=[ft.ElevatedButton("OK", on_click=fechar)],
        actions_alignment=ft.MainAxisAlignment.END
    )

    def yes():
        janela.dialog = popup
        popup.open = True
        janela.update()

    def MotionMouse(event):
        # 计算有效随机范围,避免按钮移出窗口可视区域
        max_top = janela.height - botao_No.height
        max_left = janela.width - botao_No.width
        botao_No.top = random.randint(0, int(max_top)) if max_top > 0 else 0
        botao_No.left = random.randint(0, int(max_left)) if max_left > 0 else 0
        janela.update()

    pergunta = ft.Text("Do you want to close the window?!", scale=3)
    botao_Yes = ft.ElevatedButton("Yes", on_click=yes)
    # 初始化按钮定位属性,绑定on_hover事件
    botao_No = ft.ElevatedButton("No", top=50, left=0, on_hover=MotionMouse)

    # 使用Stack容器实现绝对定位
    stack = ft.Stack(
        controls=[pergunta, botao_Yes, botao_No],
        width=janela.width,
        height=janela.height
    )

    janela.add(stack)
    janela.window_prevent_close = False
    janela.update()

ft.app(target=main, assets_dir="assets")

关键修改说明

  • 引入Stack容器:将所有控件放入Stack中,使控件的top/left属性生效,支持自由定位。
  • 替换为on_hover事件:精准匹配鼠标悬停触发移位的需求,避免点击或焦点事件的误触发。
  • 优化随机范围:通过窗口尺寸减去按钮自身尺寸,确保按钮始终在可视区域内,提升交互体验。
  • 初始化left属性:为按钮设置初始left=0,避免定位逻辑异常。

内容的提问来源于stack exchange,提问作者Ramon Alves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:32:58