如何在Flet中更新被外部程序替换的同名图像帧?
解决Flet中实时更新替换后图像的问题
核心问题分析
- Flet基于Web技术栈,会自动缓存图像资源,直接替换本地同名文件后,Flet仍会加载缓存中的旧图像。
- 你示例代码中时间戳的拼接方式错误:
src=f'Python\\plate_0.jpg{time.time()}'会生成类似Python\plate_0.jpg1699999999的无效路径,导致图像加载失败显示空白。
可行解决方案
方案1:添加查询参数绕过缓存
在图像路径后添加?ts=时间戳作为查询参数,Flet会将其视为新资源,重新加载本地文件,同时保留正确的文件名。
修正后的示例代码:
import time import flet as ft def main(page: ft.Page): # 初始图像,带初始时间戳避免缓存 i = ft.Image(src='Python/plate_0.jpg?ts={time.time()}') def animate(e): # 更新为带新时间戳的图像路径 sw.content = ft.Image( src=f'Python/plate_0.jpg?ts={time.time()}' ) page.update() sw = ft.AnimatedSwitcher( i, transition=ft.AnimatedSwitcherTransition.SCALE, duration=500, reverse_duration=500, switch_in_curve=ft.AnimationCurve.BOUNCE_OUT, switch_out_curve=ft.AnimationCurve.BOUNCE_IN, ) page.add(sw, ft.ElevatedButton("Animate!", on_click=animate)) ft.app(target=main)
注意:路径推荐使用正斜杠/,避免Windows反斜杠的转义问题。
方案2:直接加载图像字节流(更稳定)
读取本地图像文件的字节数据,赋值给Image.src_bytes,完全绕开文件缓存机制,适合实时更新的场景。
示例代码:
import time import flet as ft from PIL import Image import io def get_image_bytes(path): # 读取图像并转为字节流 with Image.open(path) as img: img_byte_arr = io.BytesIO() img.save(img_byte_arr, format='JPEG') return img_byte_arr.getvalue() def main(page: ft.Page): # 初始加载字节流 img_bytes = get_image_bytes('Python/plate_0.jpg') i = ft.Image(src_bytes=img_bytes) def animate(e): # 重新读取最新图像的字节流 new_img_bytes = get_image_bytes('Python/plate_0.jpg') sw.content = ft.Image(src_bytes=new_img_bytes) page.update() sw = ft.AnimatedSwitcher( i, transition=ft.AnimatedSwitcherTransition.SCALE, duration=500, reverse_duration=500, switch_in_curve=ft.AnimationCurve.BOUNCE_OUT, switch_out_curve=ft.AnimationCurve.BOUNCE_IN, ) page.add(sw, ft.ElevatedButton("Animate!", on_click=animate)) ft.app(target=main)
需要提前安装Pillow:pip install pillow
额外优化:自动定时更新
如果需要和并行识别程序同步自动更新,可以添加定时任务,无需手动点击按钮:
# 在main函数中添加定时更新逻辑 def auto_update(): while True: new_img_bytes = get_image_bytes('Python/plate_0.jpg') sw.content = ft.Image(src_bytes=new_img_bytes) page.update() time.sleep(0.5) # 每0.5秒更新一次 # 启动后台线程执行定时更新 import threading threading.Thread(target=auto_update, daemon=True).start()
内容的提问来源于stack exchange,提问作者VicourtBitt
相关产品推荐
相关产品推荐

