How to connect GTK3 button click events to callbacks

5,515

Have a look at this example on how to connect events to callbacks in Gtk 3 and Python. In short, you use the connect() method to connect a signal name (which is emitted when an event such as a button click occurs) to a callback, which is the function that will handle your event.

def __init__(self):
    # Other initialization code

    # We create a button
    self.button = Gtk.Button(label="Click Here")
    # We connect the 'clicked' signal to the callback
    self.button.connect("clicked", self.on_button_clicked)

def on_button_clicked(self, widget):
    # This function will be called whenever the user presses the button
    print "Hello World"

You can also watch the Gtk3 Introduction Workshop video that is part of the Ubuntu App Showdown.

If you're using Glade, you will need to make to make sure that the on_<name-of-your-button>_clicked() callback is defined in the code as a method of your window.

If you're using Quickly, that's all you'll need to worry about.

Otherwise, you'll need to manually connect the signal to the callback. You've got two options:

  • Do it in the code with self.builder.get_object('name-of-your-button').connect() - assuming builder is the name of your Gtk.Builder() in which you've loaded your Glade UI.
  • Do it with Glade looking at the properties of your button, choosing the signals tab and then writing the name of your callback in the 'clicked' signal.
Share:
5,515

Related videos on Youtube

Xerz
Author by

Xerz

Updated on September 18, 2022

Comments

  • Xerz
    Xerz over 1 year

    So, I'm developing my 1st app with GTK3 and I don't know how to link my buttons with their respective defs. Can anyone post a tutorial, an example or some docs?

    Using next things for developing my app:

    • Ubuntu 12.04 LTS totally updated
    • Python 2.7.3
    • Obviously, GTK+ 3
    • Glade 3.12.1

    The app which I'm developing is Virtuam (candidate at the App Showdown!)

    • Reuben Swartz
      Reuben Swartz almost 12 years
      Are you trying to link the button to the event callback?
  • Xerz
    Xerz almost 12 years
    Gracias de nuevo, David... pero igualmente, estoy usando Glade para crear la interfaz, así que no funciona.
  • David Planella
    David Planella almost 12 years
    No worries, it should equally work with Glade. I've added an additional note on how to do that with Glade.
  • Xerz
    Xerz almost 12 years
    But I've done the links with a dictionary, instead of using that...
  • Xerz
    Xerz almost 12 years
    And it works! That's why I typed in the title (closed)
  • Xerz
    Xerz almost 12 years