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

Kivy FileChooserListView:如何禁用目录跳转仅保留展开功能

解决Kivy FileChooserListView禁用目录名跳转的问题

要实现仅保留箭头展开目录、禁用点击目录名跳转的功能,可以通过自定义FileChooserListView子类,拦截目录项的触摸事件来实现。以下是具体实现步骤:

方法一:重写目录项的点击触发逻辑

自定义一个继承自FileChooserListView的类,在创建每个目录项时修改其点击行为,仅允许点击箭头区域时执行原逻辑:

from kivy.uix.filechooser import FileChooserListView, FileListEntry

class NoJumpFileChooserListView(FileChooserListView):
    def _create_entry(self, fn):
        # 创建默认的目录项
        entry = super()._create_entry(fn)
        # 保存原有的点击触发方法
        original_release = entry.on_release

        def custom_release(*args):
            # 获取箭头控件(目录项的第一个子控件)
            arrow_icon = entry.children[0]
            # 检查触摸位置是否在箭头区域内
            if arrow_icon.collide_point(*entry.to_widget(*self.last_touch.pos)):
                original_release(*args)
            # 点击目录名时不执行任何操作

        # 替换目录项的点击触发方法
        entry.on_release = custom_release
        return entry

方法二:直接拦截触摸事件

通过重写on_entry_touch方法,直接过滤掉点击目录名的事件:

from kivy.uix.filechooser import FileChooserListView

class NoJumpFileChooserListView(FileChooserListView):
    def on_entry_touch(self, entry, touch):
        # 仅处理点击箭头区域的事件
        arrow_icon = entry.children[0]
        if arrow_icon.collide_point(*entry.to_widget(*touch.pos)):
            return super().on_entry_touch(entry, touch)
        # 点击目录名时返回True,阻止后续事件处理
        return True

使用自定义控件

将原来的FileChooserListView替换为自定义的NoJumpFileChooserListView即可:

self.new_file_chooser = NoJumpFileChooserListView(
    size_hint=(0.9, 0.35),
    pos_hint={"center_x": 0.5}
)
self.my_layout.add_widget(self.new_file_chooser)

原理说明

FileChooserListView的每个目录项(FileListEntry)由箭头图标和目录名称标签组成,默认点击任意区域都会触发目录跳转。通过上述两种方式,我们可以精准识别点击位置,仅允许箭头区域的操作生效,从而禁用目录名跳转的功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:11:00