Python/Glade Tutorial: Part 2 (RadioButtons)

Post your tutorials and howtos here.
User avatar
ScottQuier
Posts: 1781
Joined: 18 Jul 2013 15:55
Location: Newport News, VA

Python/Glade Tutorial: Part 2 (RadioButtons)

Postby ScottQuier » 21 Jul 2014 00:04

Since I just came through this issue this afternoon, it's time for the next installment in the continuing series of "How to Program Gtk with python and Glade".

Today's episode is Gtk RadioButtons. How to get them to work and how to use them.

First, here's the picture of where we are going (the glade file is attached below):
RadioButtonTest.jpg
RadioButtonTest.jpg (8.59 KiB) Viewed 803 times
And, here's the python code

Code: Select all

#! /usr/bin/env python3

from gi.repository import Gtk

class RadioButton(object):

    def __init__(self):
        self.builder = Gtk.Builder()
        self.builder.add_from_file('RadioButton.glade')

        # We need to create an handle for our window so
        # that we can show.
        self.window = self.builder.get_object('window1')

        # Connect the signals that we have defined in our glade
        # project.
        self.builder.connect_signals(self)
        self.window.show()

    # Close the GUI when the user clicks on the
    # window close widget in the upper right corner.
    def on_window1_destroy_event(self, *argc):
        Gtk.main_quit()

    # The parameter 'widget' is our RadioButton that
    # tripped the event handler.
    def on_radiobutton_toggled_event(self, widget):
        if widget.get_active():
            state = "on"
        else:
            state = "off"
        print((Gtk.Buildable.get_name(widget) + ' was turned ' + state))

if __name__ == '__main__':
    try:
        RadioButton()
        Gtk.main()
    except KeyboardInterrupt:
        pass
The really important part of getting RadioButtons to work is to define them as members of a group. This is done by selecting each (except the first one) in turn and clicking on the General > Group property icon to display the property dialog. Therein, select the first RadioButton and click ok. Now, they all belong to the same group as defined (by default) by the first RadioButton.

The program lets you know what is going on as you click one RadioButton after another.

Code: Select all

$ python ./RadioButton.py 
radiobutton1 was turned off
radiobutton2 was turned on
radiobutton2 was turned off
radiobutton3 was turned on
radiobutton3 was turned off
radiobutton1 was turned on
Attachments
RadioButton.glade.tar.gz
(744 Bytes) Downloaded 73 times
Scott
Quoting zerozero, "The usage of PPA's in debian-based
systems is risky at best and entails serious compatibility
problems; usually it's the best way to destroy an install"

Return to “Tutorials”

Who is online

Users browsing this forum: No registered users and 1 guest