Development Team/Almanac/sugar.graphics.toolbutton

Class: ToolButton (gtk.ToolButton)

Sugar tool buttons can be added to toolbars and used to control various activity processes. Some common tool button tasks are outlined below.

How do I create my own custom tool button?

There are several steps you need to follow in order to create a tool button:

  1. Import the ToolButton class from the sugar.graphics.toolbutton package.
  2. If you intend to have an icon for your tool button, then create an "icons" directory in your activity directory and put the icon (which is a .svg file) in to that directory. For example, the code below uses an icon called "edit-custom" that accesses an edit-custom.svg file saved in the icons directory for the activity. Here is a link with information on how to create the svg files you will need: Making_Sugar_Icons
  3. Use the code below to guide you on how to then create your button programmatically and add it to a tool bar (we add it to an EditToolbar object that was presumably created already in our code).
       from sugar.graphics.toolbutton import ToolButton
       ...
       #### CUSTOM TOOL BUTTON  
       #Create a custom tool button and add it to the edit toolbar
       customButton = ToolButton('edit-custom')
       customButton.set_tooltip(_('Custom'))
       self._edit_toolbar.insert(customButton, -1)
       customButton.show()

How do I connect my tool button to a callback?

The following code fragment connects a button to a callback ...

       #When the customButton fires a "clicked" event, call self._custom_clicked_cb
       customButton.connect('clicked', self._custom_clicked_cb)

... which is then defined elsewhere in the class.

   #CALLBACK METHOD
   def _custom_clicked_cb(self, widget):
       #Begin any callback code here


What is a tooltip and how do I set it for my tool button?

A tooltip is a brief textual description of a tool button that pops up when the mouse cursor is on the toolbutton and the user right-clicks. It is meant to be descriptive so that a user understands what a toolbutton does if it isn't immediately obvious from the icon.

     #Set the tooltip for the customButton to "Custom"
     customButton.set_tooltip(_('Custom'))


How do I reset the icon displayed for my tool button?

Your first argument to the constructor for the ToolButton class will set the initial icon used for your tool button. If you decide to change your tool button's icon later, then you must get a handle on the tool button object and do the following:

       #Reset the icon displayed for customButton
       customButton.set_icon("edit-custom");

How do I add a keyboard shortcut to my tool button?

We typically use Alt characters for shortcuts within an activity, reserving Ctrl for system shortcuts. In the example below, we add the Alt-b short cut to our custom button.

       #Add keyboard shortcut for customButton
       customButton.props.accelerator = '<Alt>b'