Sugar Code Snippets
Jump to navigation
Jump to search
This page is monitored by the OLPC team.
Toolbar
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 sugar.graphics.toolbar import Toolbar from sugar.graphics.iconbutton import IconButton from sugar.graphics.entry import Entry from sugar.graphics.optionmenu import OptionMenu from sugar.graphics.menu import MenuItem class FooActivity(activity.Activity): _ACTION_ANYTHING = 1 _ACTION_APPLES = 2 _ACTION_ORANGES = 3 def __init__(self, handle): activity.Activity.__init__(self, handle) vbox = hippo.CanvasBox() self.set_root(vbox) toolbar = Toolbar() vbox.append(toolbar) button = IconButton(icon_name='theme:stock-close') button.connect("activated", self._button_activated_cb) toolbar.append(button) entry = Entry() button.connect("activated", self._entry_activated_cb) toolbar.append(entry) option_menu = OptionMenu() option_menu.add_item(MenuItem(self._ACTION_ANYTHING, _('Anything'))) option_menu.add_item(MenuItem(self._ACTION_APPLES, _('Apples'), 'theme:stock-close')) option_menu.add_item(MenuItem(self._ACTION_ORANGES, _('Oranges'))) option_menu.add_separator() toolbar.append(option_menu) 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): logging.debug('FooActivity._button_activated_cb') def _entry_activated_cb(self, entry): logging.debug('FooActivity._entry_activated_cb')
Files
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()
Images
target = ctx.get_target() buf = target.create_similar(cairo.CONTENT_COLOR_ALPHA, w, h)
dimensions = handle.get_dimension_data() width = dimensions[0] height = dimensions[1]
- 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) ctx.paint()
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 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)
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)