image

pygtk + toolbar + toolbutton with custom image

Last night I had more trouble than I was expecting while trying to put a custom image on a toolbar button. I had already done this with tabs, normal buttons and solo. It was easy but for the toolbutton it wasn’t so obvious… maybe it was because of the hour, I don’t know.
So here goes a sample to help any one in need:

# create the pixbuf with the image and it's size.
# 24,24 is the TaskEditor's toolbar icon size
# the path gets the current document path to use with the image
path = os.path.dirname(os.path.abspath(__file__))
icon_path = os.path.join(path, "image.png")
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(icon_path , 24, 24)
 
# create the image and associate the pixbuf
image = gtk.Image()
image.set_from_pixbuf(pixbuf)
image.show()
 
# create the toolbutton
btn = gtk.ToolButton()
btn.set_icon_widget(image)
btn.set_label("Task location")
btn.connect('clicked', self.some_method)
 
# then just add the item (btn) to the position you want
toolbar.insert(btn, position)
btn.show()

That’s all! ;)