如何使用 gio 和 python3 获取文件的图标

How to get icon for a file using gio and python3

我想使用 gtk 获取相应文件的默认图标。

我在 python3 中尝试过这个方法,但它给了我一个错误

from gi.repository import Gio as gio
from gi.repository import Gtk
import os

def get_icon_filename(filename,size):
    #final_filename = "default_icon.png"
    final_filename = ""
    if os.path.isfile(filename):
        # Get the icon name
        file = gio.File(filename)
        file_info = file.query_info('standard::icon')
        file_icon = file_info.get_icon().get_names()[0]
        # Get the icon file path
        icon_theme = gtk.icon_theme_get_default()
        icon_filename = icon_theme.lookup_icon(file_icon, size, 0)
        if icon_filename != None:
            final_filename = icon_filename.get_filename()

    return final_filename


print(get_icon_filename("/home/newtron/Desktop/Gkite_Logo.png",64))

错误

  File "geticon", line 11, in get_icon_filename
    file = gio.File(filename)
TypeError: GInterface.__init__() takes exactly 0 arguments (1 given)

我以前没有任何 gio 模块的经验。我的代码有问题吗?如果没有,这个错误的解决方法是什么。

正如我的朋友 @stovfl 所说,这是因为我在 python2 中使用旧的 Gi 和 Gtk 代码。但是在新版本的 gio.File 属性中有更多的子属性(classes) 指定什么样的文件 属性 被给出,例如

new_for_path class 我在我的代码中使用了它并且成功了。实际上我从另一个 Whosebug 讨论中得到了这段代码。

当我再次检查时,它有 python3 代码

#!/usr/bin/env python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gio as gio
from gi.repository import Gtk as gtk
import os

def get_icon_filename(filename,size):
    #final_filename = "default_icon.png"
    final_filename = ""
    if os.path.isfile(filename):
        # Get the icon name
        file = gio.File.new_for_path(filename)
        file_info = file.query_info('standard::icon',0)
        file_icon = file_info.get_icon().get_names()[0]
        # Get the icon file path
        icon_theme = gtk.IconTheme.get_default()
        icon_filename = icon_theme.lookup_icon(file_icon, size, 0)
        if icon_filename != None:
            final_filename = icon_filename.get_filename()

    return final_filename


print(get_icon_filename("/home/newtron/Desktop/counter.desktop",48))