3

I have a function that creates prompts using gtk.MessageDialog in PyGTK. How could I access the predefined buttons? Or would I need to manually construct a gtk.Dialog? I'd rather not, seeing as MessageDialog is a convenience function.

The function:

def gtkPrompt(self, name):
    # Create new GTK dialog with all the fixings
    prompt = gtk.MessageDialog(None, 0, gtk.MESSAGE_QUESTION, gtk.BUTTONS_OK_CANCEL, name)
    # Set title of dialog
    prompt.set_title("Prompt")
    # Create and add entry box to dialog
    entry = gtk.Entry()
    prompt.vbox.add(entry)
    # Show all widgets in prompt
    prompt.show_all()
    # Run dialog until user clicks OK or Cancel
    if prompt.run() == gtk.RESPONSE_CANCEL:
        # User cancelled dialog
        rval = False
    else:
        # User clicked OK, grab text from entry box
        rval = entry.get_text()
    # Destory prompt
    prompt.destroy()
    # Give the good (or bad) news
    return rval
soren121
  • 368
  • 3
  • 16

3 Answers3

4

Since 2.22 you can use get_widget_for_response() method. For example:

cancelButton = dialog.get_widget_for_response(response_id=gtk.RESPONSE_CANCEL)
Dave
  • 875
  • 6
  • 15
3

You can use get_children() to get to the "OK" button:

def yesNoDialog(window, message, default=False):
    dialog=gtk.MessageDialog(window, gtk.DIALOG_MODAL |
                             gtk.DIALOG_DESTROY_WITH_PARENT,
                             gtk.MESSAGE_QUESTION,
                             gtk.BUTTONS_YES_NO, message)
    if default:
        h_button_box=dialog.vbox.get_children()[1]
        yes_button=h_button_box.get_children()[0]
        yes_button.grab_default()
    response=dialog.run()
    dialog.destroy()
    if response==gtk.RESPONSE_YES:
        return True
    else:
        return False
guettli
  • 25,042
  • 81
  • 346
  • 663
2

gtk.MessageDialog is a subclass of gtk.Dialog. gtk.Dialog objects store their buttons in a gtk.HBox under the action_area attribute.

In code:

> prompt.action_area.get_children()
[<gtk.Button object at 0x18c0aa0 (GtkButton at 0x130e990)>, <gtk.Button object at 0x18c0af0 (GtkButton at 0x130e8d0)>]
jcollado
  • 39,419
  • 8
  • 102
  • 133