Sugar Code Snippets

Revision as of 19:25, 22 August 2009 by (talk) (Audio: avoid wildcard import)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
  This page is monitored by the OLPC team.
  english | 日本語 HowTo [ID# 215547]  +/-  

The Sugar Almanac also has lots of code snippets.

Smooth animation



Use the WebView in a widget.

import os
import hulahop
from sugar import env
hulahop.startup(os.path.join(env.get_profile_path(), 'gecko'))

from hulahop.webview import WebView

import gtk

win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.connect('destroy', gtk.main_quit)
wv = WebView()


WebView DOM manipulation example

For an example which performs DOM-level manipulation of the browser (getElementsById, appendChild all in python NOT repeat NOT javascript) see

The example shows how it is necessary to wait until the URI has been loaded before the DOM document is ready and can be manipulated using DOM functions. The example includes a progress listener which fires a callback, in which the DOM manipulation is performed. The words "hello world" are added and the body style changed to green.


  • I'm not sure what the purpose is of the call to hulahop.startup as the documentation is rather sparse. I only knows it's needed to get it to work Stas Zytkiewicz 2 Dec 2007

lkcl: it's for the gecko engine to store exactly the same state information that e.g. firefox stores in e.g. ~/.mozilla/


Toolbar icons

Setting a standard Sugar toolbar.

from sugar.activity import activity
class MyActivity(activity.Activity):
   toolbox = activity.ActivityToolbox(self)

Adding a custom toolbar and icons.

from import ToolButton
from sugar.activity import activity
class MyActivity(activity.Activity):
   mytoolbox = gtk.Toolbar()
   helpbut = ToolButton('help') #Stock help icon
   helpbut.set_tooltip(_("Get help"))
   helpbut.connect('clicked', self.help_button_pressed)
   mytoolbox.insert(helpbut, -1)

   toolbox = activity.ActivityToolbox(self)

In addition to the standard icons in /usr/share/icons/sugar/scalable/ (eg, "go-next"), you can create additional icons by putting an svg in your activity's icons/ directory. E.g.,


And then use it.

mybut = ToolButton('my-icon')# without extension


This snippet shows how to get a path to files in the running Activity:

from sugar.activity import activity
bundle_path = activity.get_bundle_path()

This snippet shows how to get a path to an activity's writable directories (i.e. the SUGAR_ACTIVITY_ROOT environment variable; see also the activity DBus API):

class WebActivity(activity.Activity):
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)
        temp_path = os.path.join(self.get_activity_root(), 'instance')


target = ctx.get_target()
buf = target.create_similar(cairo.CONTENT_COLOR_ALPHA, w, h)
ctx.set_source_surface(buf, x, y)
width, height = handle.get_dimension_data()
  • Loading a JPEG file onto a surface:
pixbuf = gtk.gdk.pixbuf_new_from_file("foo.jpg")
ctx = # a cairo context
ctx.set_source_pixbuf(pixbuf, 0, 0)

libjpeg is said to be an alternative to using pixbuf. Which is better? Perhaps Sugar/HippoCanvas provides an easier way to do this?

Cairo image expansion is good quality, but expensive. Shrinking is fine and notably faster. So for images rendered large (ie, screen-size), you might want to start with a big image, rather than expanding a small one. A speed/space tradeoff. And use SVG instead if appropriate, of course. MitchellNCharity 10:37, 10 May 2007 (EDT)


import sys
from sound import playWave, audioOut


Use Python's subprocess module.
Set the "exec" property of the file to your binary.

Not yet sorted

from sugar import profile

key = profile.get_pubkey()

# If you want a shorter key, you can hash that like:

from sugar import util

key_hash = util._sha_data(key)
hashed_key = util.printable_hash(key_hash)
  • Avoid memory exhaustion from large dead pygtk objects by using
import gc

Not all trash pygtk objects are garbage collected promptly. If you are throwing away large pixmaps, for instance, this can be deadly. gc.collect() forces a garbage collection pass.

Performance Tips

This section belongs on a different, as yet non-existent page. But a good organization for software development tips is currently unclear to me, so I'll stash this here for now. MitchellNCharity 14:05, 10 May 2007 (EDT)

  • ctx.stroke() several lines at once. stroke() currently has significant overhead. So it is faster to stroke several, than to stroke them individually. They need not be contiguous. MitchellNCharity 14:05, 10 May 2007 (EDT)

Old snippets which need to be overhauled


This snippet shows how an activity would have a toolbar with a button and a gtk.TextView widget embedded in a hippo Canvas:

import logging
import hippo
import gtk

from gettext import gettext as _

from sugar.activity import activity
from import Toolbar
from import IconButton
from import Entry
from import OptionMenu
from import MenuItem

class FooActivity(activity.Activity):


   def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        vbox = hippo.CanvasBox()

        toolbar = Toolbar()

        button = IconButton(icon_name='theme:stock-close')
        button.connect("activated", self._button_activated_cb)

        entry = Entry()
        button.connect("activated", self._entry_activated_cb)

        option_menu = OptionMenu()
        option_menu.add_item(MenuItem(self._ACTION_ANYTHING, _('Anything')))
        option_menu.add_item(MenuItem(self._ACTION_APPLES, _('Apples'),
        option_menu.add_item(MenuItem(self._ACTION_ORANGES, _('Oranges')))

        text_view_widget = hippo.CanvasWidget()
        vbox.append(text_view_widget, hippo.PACK_EXPAND)

        text_view = gtk.TextView()
        text_view.get_buffer().set_text('Write here!', -1)
        text_view_widget.props.widget = text_view

    def _button_activated_cb(self, button):

    def _entry_activated_cb(self, entry):
In build 443 (June '07), from import Entry yields ImportError: No module named entry. MitchellNCharity 19:52, 15 June 2007 (EDT)
And obsolete, now deleted code like is being used. Snippet needs to be overhauled. MitchellNCharity 18:04, 21 June 2007 (EDT)