首页 > 解决方案 > 如何使用 gio 和 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 模块方面没有任何经验。我的代码有问题吗?如果它没有解决此错误的方法是什么。

标签: python-3.xgtk3gio

解决方案


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

new_for_path类我在我的代码中使用了它并工作了它。实际上我从另一个 StackOverflow 讨论中得到了这段代码。

当我再次检查它时,它有 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))

推荐阅读