Adding GTK-3 buttons and switches


Figure 1: Display GTK-3 Buttons and switches

The example below loads 4 buttons from a glade 2 standard and 2 toggle buttons, it then connects event handles to show some text when clicked or to show the toggle state if a toggle button was clicked.

from gi.repository import Gtk

class application_gui:
    """Tutorial 02 buttons"""

    def __init__(self):
	#load in our glade interface
	xml = Gtk.Builder()

	#grab our widget using get_object this is the name of the widget from glade, window1 is the default name
	self.window = xml.get_object('window1')
	self.text = xml.get_object('entry1')

	self.buttons = {}
	self.buttons['but1'] = xml.get_object('button1')
	self.buttons['but2'] = xml.get_object('button2')
	self.buttons['but3'] = xml.get_object('togglebutton1')
	self.buttons['but4'] = xml.get_object('togglebutton2')

	self.buttons['but1'].connect('clicked', self.button_events)
	self.buttons['but2'].connect('clicked', self.button_events)
	self.buttons['but3'].connect('clicked', self.button_events)
	self.buttons['but4'].connect('clicked', self.button_events)

	#connect to events, in this instance just quit our application
	self.window.connect('delete_event', Gtk.main_quit)
	self.window.connect('destroy', lambda quit: Gtk.main_quit())

	#show the window else there is nothing to see :)

    def button_events(self, widget):
	toggle_value = ''
	if widget.get_name() == 'GtkToggleButton':
	    toggle_value = str(widget.get_active())
	self.text.set_text(widget.get_name() + ' ' +widget.get_label()+ ' ' + toggle_value)

application = application_gui()