PyGTK: Get GNOME icon associated with a file
If in your application you need to display a list of files/folders it would be nice to display icons near filenames.
Icons are associated with files using mime types. For a file you need to get it’s mime and the get the icon associated with this mime.
The module gnomevfs provides almost all you need:
- def gnomevfs.get_mime_type(uri)
Returns a string containing the mime type (ex: for the file “file.tar.gz” the mime is “application/x-compressed-tar”).
- def gnomevfs.mime_get_icon(mime_type)
Returns a string with an icon name.
I said almost because gnomevfs.mime_get_icon always returns None (at least in my version).
Since the gnomevfs.get_mime_type works fine I decide to write a little class to associate the mime with the icons.
Gnome use icon names like “gnome-mime-<mime>”. Ex: for the mime “application/x-compressed-tar” the gnome icon name is “gnome-mime-application-x-compressed-tar”.
My class try to associate the mime with an icon, by searching for icons with the name:
- “gnome-mime-<mime>”
- if the path is a directory it will try the icon name “folder” and if “folder” don’t exists just returns gtk.STOCK_DIRECTORY
- “mime-<mime>”
- returns gtk.STOCK_FILE
In order to optimize mime to icon association the class use a cache.
import os.path import pygtk pygtk.require("2.0") import gtk import gnomevfs class GnomeFileIcons: def __init__( self ): self.all_icons = gtk.icon_theme_get_default().list_icons() self.cache = {} def getIcon( self, path ): if not os.path.exists(path): return gtk.STOCK_FILE #get mime type mime_type = gnomevfs.get_mime_type( path ).replace( '/', '-' ) #search in the cache if mime_type in self.cache: return self.cache[mime_type] #try gnome mime items = mime_type.split('-') for aux in xrange(len(items)-1): icon_name = "gnome-mime-" + '-'.join(items[:len(items)-aux]) if icon_name in self.all_icons: #print "icon: " + icon_name self.cache[mime_type] = icon_name return icon_name #try folder if os.path.isdir(path): icon_name = 'folder' if icon_name in self.all_icons: #print "icon: " + icon_name self.cache[mime_type] = icon_name return icon_name #print "icon: " + icon_name icon_name = gtk.STOCK_DIRECTORY self.cache[mime_type] = icon_name return icon_name #try simple mime for aux in xrange(len(items)-1): icon_name = '-'.join(items[:len(items)-aux]) if icon_name in self.all_icons: #print "icon: " + icon_name self.cache[mime_type] = icon_name return icon_name #file icon icon_name = gtk.STOCK_FILE self.cache[mime_type] = icon_name return icon_name
Using it is very simple:
import gnomefileicons fileicons = gnomefileicons.GnomeFileIcons() print fileicons.getIcon('/path/file.tar.gz')

February 22nd, 2009 at 7:26 pm
Is there a solution with the gvfs? Since gnomevfs will be depreciated
February 22nd, 2009 at 10:14 pm
There is a python binding for gvfs ?