Wednesday, November 30, 2011

GTK Quick Tip - Toggling icons on toolbars

Just a quick tip when using GTK to try and set up a toggle button, with an icon that changes appearance when the state changes.
When initialising the images for use on the button, remember to do ".show()" on BOTH of the icons, otherwise, only the one visible on the button on startup will be visible later on.
Disclaimer:  I'm still getting my head around GTK (PyGTK), so the following code snippet may not be considered "best practice" in these cricles.

# "Lock" toolbar toggle
class LockToolbarToggle(gtk.ToggleToolButton):
# Class Constants ======================== 
# (gtk.Image) icon widgets for the states; Initialised on first use
LOCKED   = None

# Setup ===================================

# ctor
# < label_template: (str) label for the item, with format placeholders for 
#                           lock/unlock substitution
# < tooltip_template: (str) tooltip for the item, with format palceholders 
#                           for lock/unlock substitution
def __init__(self, label_template, tooltip_template):
# init settings

self.label_template = label_template
self.tooltip_template = tooltip_template

# set up icons to use
# NOTE: as last step of init, we must "show" the icon, otherwise it 
# won't show up later when toggled
if LockToolbarToggle.LOCKED is None:
LockToolbarToggle.LOCKED = gtk.Image()
if LockToolbarToggle.UNLOCKED is None:
LockToolbarToggle.UNLOCKED = gtk.Image()

# register callback for updating displayed state on state-change
# and call this once with dummy args to set the right values
self.connect("toggled", self.state_changed_cb, None)

# Signals =================================

# callback for updating visual state on state change
def state_changed_cb(self, widget, data=None):
if self.get_active():
self.set_label(self.label_template % ("Unlock"))
self.set_tooltip(self.tooltip_template % ("Disable"))
self.set_label(self.label_template % ("  Lock"))
self.set_tooltip(self.tooltip_template % ("Enable"))

No comments:

Post a Comment