All pastes #885584 Raw Edit

XO Example Activity

public text v1 · immutable
#885584 ·published 2008-01-30 23:56 UTC
rendered paste body
import pygtk
pygtk.require('2.0')
import gtk, sys, random, time

from sugar.activity import activity

class ExampleActivity(activity.Activity):

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

        self.set_title("Simple Graphical Activity")

        # Show the toolbox elements
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()

        # Register the even callbacks
        self.connect("expose_event", self.area_expose_cb)
        self.connect("key_press_event", self.keypress_cb)
        self.connect("button_press_event", self.button_press_cb)
        self.show()
        
        # Seed the random number generator
        random.seed(time.time())

        self.area = self.window
        self.gc = self.area.new_gc()

        # Allocate a color dictionary
        self.colors = {}
        self.colormap = self.gc.get_colormap()
        self.colors[0] = self.colormap.alloc_color('green')
        self.colors[1] = self.colormap.alloc_color('blue')
        self.colors[2] = self.colormap.alloc_color('black')
        self.colors[3] = self.colormap.alloc_color('red')

        # Register for events
        self.area.set_events(
            gtk.gdk.EXPOSURE_MASK       |
            gtk.gdk.KEY_PRESS_MASK      |
            gtk.gdk.LEAVE_NOTIFY_MASK   |
            gtk.gdk.BUTTON_PRESS_MASK  )

    def draw_box(self, x, y):
        self.gc.set_foreground(self.colors[random.randint(1,3)])
        self.area.draw_rectangle(self.gc, True, x, y, 50, 50)
        self.area.show()

    def area_expose_cb(self, area, event):
        self.gc_set_foreground(self.colors[0])
        self.area.draw_rectangle(self.gc, True, 200, 200, 400, 400)
        self.area.show()

        return True

    def keypress_cb(self, widget, event):
        sys.exit()

    def button_press_cb(self, widget, event):
        if event.button == 1:
            self.draw_box(event.x, event.y)

            return True