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-”. 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-
  • 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-
  • returns gtk.STOCK_FILE

In order to optimize mime to icon association the class use a cache.

 


Using it is very simple:

import gnomefileicons
 
fileicons = gnomefileicons.GnomeFileIcons()
print fileicons.getIcon('/path/file.tar.gz')

Tags: , , , , ,

3 Responses to “PyGTK: Get GNOME icon associated with a file”

  1. Vadi Says:

    Is there a solution with the gvfs? Since gnomevfs will be depreciated

  2. dan Says:

    There is a python binding for gvfs ?

  3. Sebas310 Says:

    Where is this gnomefileicons file?

Leave a Reply