Pygtk: Check to see if a button is sensitive

Setting and unsetting flags is a no-brainer, but how do you just check to see if a flag such as ‘gtk.SENSITIVE’ is set for something like a button? Here’s an example of how easy it is.

Use the bitwise and operator, ‘&’ with the flag you’re interested in.

It’s pretty simple but hard to find this answer when you’re looking for a method to extract a bool value. I wish it was as easy as using ‘is_sensitive()’ that returns true if the widget flag ‘gtk.SENSITIVE’ is set. But use the ampersand with the flags and you’re all set.

two power buttons on silver

This is specifically for pygtk and only applicable to buttons, really you should be moving to QT because everything from documentation to implementation of a button is that just much smoother.

Here’s a short example of checking for a save button’s sensitivity before proceeding to quit the main loop. This is something you may use when a quit button is clicked but changes have been made to a document and you want to give the user one last chance to save before exiting your application.

def quit(self, widget):
  if self.button_save.flags() & gtk.SENSITIVE:
    msg = "Save changes before closing?"
    dialog = gtk.MessageDialog(None, gtk.DIALOG_DESTROY_WITH_PARENT,
            gtk.MESSAGE_INFO, gtk.BUTTONS_YES_NO, msg)
    dialog.set_title("There are unsaved Changes")

    response =
    if response != gtk.RESPONSE_YES:
      return False