Adding switch and radio widgets



tut03-switch-radio.png

Figure 1: Adding radio buttons & switches

The below sample shows loading and retrieving state values for radio buttons and switches.

#!/usr/bin/python
from gi.repository import Gtk


class application_gui:
    """Tutorial 03 Radio Buttons and switches"""

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

	#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['radio1'] = xml.get_object('radiobutton1')
	self.buttons['radio2'] = xml.get_object('radiobutton2')
	self.buttons['switch1'] = xml.get_object('switch1')
	self.buttons['switch2'] = xml.get_object('switch2')

	#set a name of the switches because they dont have a label so we can use this to show selected button
	self.buttons['switch1'].set_name('switch1')
	self.buttons['switch2'].set_name('switch2')

	#connect the interface events to functions
	self.buttons['switch1'].connect('button-press-event', self.switch_button_events)
	self.buttons['switch2'].connect('button-press-event', self.switch_button_events)
	self.buttons['radio1'].connect('toggled', self.radio_button_events)
	self.buttons['radio2'].connect('toggled', self.radio_button_events)

	#add the second radio to the first radio button making it part of the group
	self.buttons['radio2'].join_group(self.buttons['radio1'])

	#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 :)
	self.window.show()

    def switch_button_events(self, widget, params):
	toggle_value = str(widget.get_active())
	self.text.set_text(widget.get_name() + ' ' + toggle_value)

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


application = application_gui()
Gtk.main()

Comments