python-3.xgtk3gio

How to get icon for a file using gio and python3


I want to get the default icon for a corresponding file using gtk.

I tried this method in python3 but it gave me an error

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))

Err

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

I don't have any previous experience in gio module. Does my code have any problem? If it has not what is the solution to this error.


Solution

  • As my friend @stovfl said it was because I was using the old Gi and Gtk codes for python2. But in the new version of gio.File attribute has more sub-attributes(classes) that specify what kind of file property is given such as

    new_for_path class I used this in my code and worked it. Actually I got this code from another StackOverflow discussion.

    When I checked it again it had the python3 code

    #!/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))