Load an Image and detect click events in Python
Code snippet to render a graphic using clutter and detect user click on the image, also demonstrates using the clutter library in a functional style and OO style.
# [SNIPPET_NAME: Load an Image and detect click events] # [SNIPPET_CATEGORIES: Clutter] # [SNIPPET_DESCRIPTION: Render a graphic using clutter and detect user click on the image, also demonstrates using the clutter library in a functional style and OO style] # [SNIPPET_AUTHOR: Oliver Marks <oly@digitaloctave.com>] # [SNIPPET_LICENSE: GPL] import clutter #create a clutter stage and set the display size stage = clutter.Stage() stage.set_size(400, 400) #load the image for the buttons img=clutter.cogl.texture_new_from_file('button.png',clutter.cogl.TEXTURE_NO_SLICING, clutter.cogl.PIXEL_FORMAT_ANY) #example create button from class start class button(clutter.Texture): def __init__(self,id,row=1,padding=10): clutter.Texture.__init__(self) self.row=row self.id=id self.set_size (100,100) self.set_position (id*100,self.row*100) self.set_cogl_texture(img) self.set_reactive(True) #call click method on button clicked self.connect("button-press-event",self.clicked) def clicked(self,stage, event): print "class click="+str(self.id)+" row "+str(self.row) #list of button class buttonlist1=[] for i in range(0,10): buttonlist1.append(button(i)) #add the buttons to the stage for b in buttonlist1: stage.add(b) #example create button from class end #example class with collection of button class class buttons: def __init__(self): self.buttonlist=[] self.count=0 for i in range(0,10): self.buttonlist.append(button(self.count,row=2)) #stage.add(self.buttonlist[self.count]) self.count+=1 #iter method so we can step through all buttons in a for loop def __iter__(self): for i in self.buttonlist: yield i #append a new button def append(self,btton): self.buttonlist.append(self.count) self.count+=1 #crate instance of buttons class #append buttons class to stage buttonlist2=buttons() for b in buttonlist2: stage.add(b) #example class with collection of button class end #example of creating button with function calls start #function call back on hit of button def button_click(stage, event): print "no class test button press" rectangle_actor = clutter.Texture() rectangle_actor.set_size (100,100) rectangle_actor.set_cogl_texture(img) rectangle_actor.set_reactive(True) #call button_click function rectangle_actor.connect("button-press-event", button_click) #add non class button stage.add(rectangle_actor) #example of creating button with function calls end #show everything in the stage stage.show_all() stage.connect("destroy",clutter.main_quit) #main clutter loop clutter.main()