How can I create a group of radio buttons

A radio button is a widget that allows the user to choose from among several options. Unlike checkboxes, radio buttons are explicitly deployed in groups and only one of the options can be selected at a time. When a new option is selected, the existing selection is switched off. The name radio button comes from the group of selection buttons on older car radios that exhibited the same behavior. Radio buttons are a bit more complex to use than checkboxes, because they need to be organized into a group in order to be useful.

In wxPython, there are two ways to create a group of radio buttons. One of them, wx.RadioButton, requires you to create the buttons one at a time, while wx.RadioBox allows you to deploy an entire group of buttons with a single object, displaying the buttons in a rectangle.

The wx.RadioButton class is simpler, and is preferred in the case where the radio buttons have a direct influence on other widgets, or where the layout of the radio buttons is not in a simple rectangle. Figure 7.11 displays an example of a few wx.RadioButton objects in a group.

Figure 7.11 Example of wx.RadioButton where radio buttons enable text control

We are using wx.RadioButton in this example because each radio button controls an associated text control. Since widgets outside the radio button group are involved, we can't just use a radio box.

How to create radio buttons

Listing 7.11 displays the code for figure 7.11, which manages the relationship between the radio buttons and the text controls.

Listing 7.11 Using wx.RadioButton to control another widget import wx class RadioButtonFrame(wx.Frame):

wx.Frame._init_(self, None, size=(2 00, 200)) panel = wx.Panel(self, -1)

radio1 =







radio2 =





radio3 =





text1 = wx.TextCtrl(panel, -1, text2 = wx.TextCtrl(panel, -1, text3 = wx.TextCtrl(panel, -1, self.texts = {"Elmo": text1, "Ernie" for eachText in [text2, text3]:

eachText.Enable(False) for eachRadio in [radio1, radio2, radio3]: <-self.Bind(wx.EVT_RADIOBUTTON, self.OnRadio, self.selectedText = text1

pos=(20, 80)) pos=(20, 110)) pos=(80, 50)) < pos=(80, 80)) pos=(80, 110))

text2, "Bert": text3}

Creating text controls

Linking buttons and text^ <_| Binding events eachRadio)

def OnRadio(self, event): <— Event handler if self.selectedText:

self.selectedText.Enable(False) radioSelected = event.GetEventObject() text = self.texts[radioSelected.GetLabel()] text.Enable(True) self.selectedText = text if _name_ == '_main_':

app = wx.PySimpleApp()



We've created radio buttons and text boxes, then initialized a dictionary containing the connections between them. A for loop disables two of the text boxes, and another one binds the radio button command event. When the event is clicked, the currently active text box is disabled, and the box matching the clicked button is enabled.

Using wx.RadioButton is similar to wx.CheckBox. The constructor is nearly identical, as in the following:

wx.RadioButton(parent, id, label, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, validator=wx.DefaultValidator, name="radioButton")

As in the checkbox, the label is used for the caption displayed next to the button.

The wx.RB_GROUP style declares the button to be the beginning of a new group of radio buttons. The definition of a group of radio buttons is important because it governs toggle behavior. When one button in the group is selected, the previously selected button in the group is toggled to the unchecked state. After a radio button is created with wx.RB_GROUP, all subsequent radio buttons added to the same parent are added to the same group. This continues until another radio button is created with wx.rb_group, starting the next group. In listing 7.11, the first radio button is declared with wx.RB_GROUP, and subsequent ones are not. The result of this is that all the buttons are considered to be in the same group, and clicking on one of them toggles off the previously selected button.

Using a radio box

Typically, if you want to display a group of buttons, declaring them separately is not the best method. Instead, wxPython allows you to create a single object that encapsulates the entire group using the class wx.RadioBox. As displayed in figure 7.12, it looks very similar to a group of radio buttons.

To use the wx.RadioBox class, all you need is the constructor. Listing 7.12 displays the code that created figure 7.12.

Listing 7.12 Building a radio box import wx class RadioBoxFrame(wx.Frame):

wx.Frame._init_(self, None, -1, 'Radio Box Example',

— Radio Box Example


A Radio Box O zero O one O'wo O three

O Five

Ofour ©Five



O eight

O si* O seven

O eight

Figure 7.12 Two examples of wx.RadioBox built from the same underlying data with different configurations

Figure 7.12 Two examples of wx.RadioBox built from the same underlying data with different configurations size=(350, 200)) panel = wx.Panel(self, -1)

sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',

'six', 'seven', 'eight'] wx.RadioBox(panel, -1, "A Radio Box", (10, 10), wx.DefaultSize, sampleList, 2, wx.RA_SPECIFY_COLS)

wx.RadioBox(panel, -1, "", (150, 10), wx.DefaultSize, sampleList, 3, wx.RA_SPECIFY_COLS)

if __name__ == '__main__': app = wx.PySimpleApp() RadioBoxFrame().Show() app.MainLoop()

The constructor for wx.RadioBox is more complex than the simple radio button, since you need to specify the data for all the buttons at once, as in the following:

wx.RadioBox(parent, id, label, pos=wx.DefaultPosition, size=wxDefaultSize, choices=None, majorDimension=0, style=wx.RA_SPECIFY_COLS, validator=wx.DefaultValidator, name="radioBox")

There are a few arguments to the constructor that are unfamiliar or different. In this constructor, the label argument is the static text which is displayed on the border of the box. The buttons themselves are specified in the choices argument, which is a Python sequence of the string labels.

Like a grid sizer, you specify the dimensions of a wx.RadioBox by stating the size in one dimension, and wxPython fills as many slots in the other dimension as needed. The major dimension size is specified in the majorDimension argument. Which dimension is considered major depends on the style flag. The default value, which is also used for the example in listing 7.12 and figure 7.12, is wx.ra_specify_cols. In the example, the number of columns is set to 2 (in the left box) or 3 (in the right box), and the number of rows is determined dynamically by the number of elements in the choices list. If you want the opposite behavior, set the style to wx.ra_specify_rows. If you want to respond to the command event when a radio box is clicked, the event is evt_radiobox.

The wx.RadioBox class has a number of methods to manage the state of the various radio buttons inside the box. For the methods that allow you to manage a specific internal button, pass the index of the button. The indexes start at 0 and proceed in the exact order that was used when the button labels were passed to the constructor. Table 7.11 lists the methods.

Table 7.11 Methods of wx.RadioBox



EnableItem(n, flag)

The flag argument is a Boolean which is used to enable or disable the button at index n. To enable the entire box at once, use Enable().


Returns the integer index of the button with the given label, or -1 if the label is not found.


Returns the number of buttons in the box.

GetltemLabel(n) SetItemLabel(n, string)

Returns or sets the string label of the button at index n.

GetSelection() GetStringSelection() SetSelection(n) SetStringSelection( string)

The Getselection() and setselection() methods manage the integer index of the currently selected radio button. Getstringselection() returns the string label of the currently selected button, while setstringselection() changes the selection to the button with the given string. Neither of the setter functions causes an EVT_RADIOBOX to be sent.

Showltem(item, show)

The show argument is a Boolean used to display or hide the button at index item.

Radio buttons aren't the only way to give the user a choice of a series of options. List and combo boxes often take up less space, and can also be configured to allow the user to make multiple selections from the same group.

Was this article helpful?

+2 -3


  • celendine
    How to use radio button in wx python?
    2 years ago
  • balbo fairbairn
    How to create radio button in python?
    10 months ago
  • irene
    How to make two ooposing radio buttons in pyqt?
    10 months ago

Post a comment