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

如何在Kivy的.kv文件中定时重新加载图片?

如何定时更新KivyMD中.kv文件内的FitImage图片

要定时更新.kv文件里指定FitImage的图片,核心是在Python代码中定位到该组件,然后更新其source属性并处理图片缓存问题,具体步骤如下:

1. 给目标FitImage添加ID

修改你的swiper.kv文件,给需要更新的FitImage加上id,方便后续在Python中获取:

<MySwiper@MDSwiperItem>

MDScreen:
    MDSwiper:
        id: swiper
        size_hint_y: None
        height: root.height - dp(40)
        y: root.height - self.height - dp(20)

        on_swipe:
        on_pre_swipe:
        on_overswipe_right:
        on_overswipe_left:

        MySwiper:
            FitImage:
                id: target_image  # 添加这个ID
                source: "./images/screen.png"
                radius: [20,]
   
        MySwiper:
            FitImage:
                source: "images/bild2.png"
                radius: [20,]
        
        MySwiper:
            FitImage:
                source: "images/bild3.png"
                radius: [20,]

2. 修改Python代码实现定时更新

更新main.py,实现update方法,定位到目标组件并更新图片,同时清除Kivy的图片缓存(避免同一文件内容变化时显示旧图):

from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.clock import Clock
from kivy.core.image import Image as CoreImage

class MainApp(MDApp):
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "BlueGray"
        Clock.schedule_interval(self.update, 1)  # 每秒执行一次update
        self.root = Builder.load_file("swiper.kv")
        return self.root

    def update(self, dt):
        # 定位目标FitImage组件:遍历swiper的所有item找到带target_image的组件
        target_image = None
        for item in self.root.ids.swiper.get_items():
            if hasattr(item, 'ids') and 'target_image' in item.ids:
                target_image = item.ids.target_image
                break
        
        if not target_image:
            return
        
        img_path = "./images/screen.png"
        # 清除Kivy的图片缓存,确保加载最新内容
        if img_path in CoreImage._cache:
            del CoreImage._cache[img_path]
        
        # 先清空source再重新赋值,触发组件重新加载图片
        target_image.source = ""
        target_image.source = img_path

MainApp().run()

关键说明

  • 组件定位:用get_items()遍历swiper的所有项,比直接通过子组件索引更可靠,避免组件顺序变化导致找不到目标
  • 缓存处理:Kivy会缓存已加载的图片,如果是同一文件内容动态变化,必须清除缓存才能显示新图
  • 触发更新:先将source设为空再重新赋值,强制FitImage重新加载图片资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:22:59