Adding switch and radio widgets
rss_feed

Adding switch and radio widgets

homeHome
pagesGTK-3
pagespython
pageswidgets

Adding radio buttons & switches

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/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()