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

Gtk+3报错‘GLocalFile’未定义,求文件管理器侧边栏代码修复方案

解决Gtk+3中‘GLocalFile’未定义的错误

嘿,这个问题我之前也碰到过,其实是对Gio和Gtk的API理解有点小偏差,我来帮你搞定!

问题根源

你代码里的GLocalFile.get_uri(location)调用有两个问题:

  1. GLocalFile是Gio模块下的类,但你没有正确引用它(而且就算引用了也没必要);
  2. 更关键的是——placessidebar.get_location()返回的对象本身就是Gio.File的实例(GLocalFile是它处理本地文件的子类),直接调用这个实例的get_uri()方法就能拿到URI,完全不需要绕到GLocalFile。

修正后的代码

我把你的代码调整了一下,修复了错误,还补全了信号连接的正确写法(原来的connect("...")是占位符对吧?):

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import Gio

def on_open_location(placessidebar, location, flags):
    # 直接调用location实例的get_uri()方法即可
    print("Opened URI: %s" % (location.get_uri()))

def create_side_bar():
    placessidebar = Gtk.PlacesSidebar()
    placessidebar.set_open_flags(Gtk.PlacesOpenFlags.NORMAL)
    # 正确连接"open-location"信号到回调函数
    placessidebar.connect("open-location", on_open_location)
    
    # 额外加个窗口测试用(你可以根据自己的需求调整)
    window = Gtk.Window(title="Places Sidebar Demo")
    window.add(placessidebar)
    window.connect("destroy", Gtk.main_quit)
    window.show_all()
    Gtk.main()

# 启动侧边栏示例
create_side_bar()

额外说明

如果之后你需要判断某个Gio.File实例是不是本地文件,可以用isinstance(location, Gio.LocalFile)(注意是驼峰式的LocalFile,不是GLocalFile——GObject introspection绑定后类名会调整成符合Python风格的命名),但在这个场景下完全不需要这么做。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:25:39