How can I display a list of choices in a dialog

If allowing your users a blank text entry seems like too much freedom, you can restrict their options by using wx.Single-ChoiceDialog to give them a single choice out of a group of options. Figure 9.4 displays an example.

The essential code displayed in listing 9.4 is similar to the dialog examples we've already discussed in this chapter.

Listing 9.4 Displaying a dialog list of choices import wx if _name_ == "_main_":

app = wx.PySimpleApp()

choices = ["Alpha", "Baker", "Charlie", "Delta"] dialog = wx.SingleChoiceDialog(None, "Pick A Word", "Choices", choices)

print "You selected: %s\n" % dialog.GetStringSelection() dialog.Destroy()

The constructor for the wx.SingleChoiceDialog is as follows:

wx.SingleChoiceDialog(parent, message, caption, choices, clientData=None, style=wx.OK | wx.CANCEL | wx.CENTRE, pos=wx.DefaultPosition)

The message and caption arguments are as before, displaying the prompt in the dialog and the title bar, respectively. The choices argument takes a Python list of strings, and they are, as you might suspect, the choices presented in the dialog. The style argument has the three options that are in the default, allowing an OK button, a Cancel button, and the option to center the dialog on the screen. The

Wxsinglechoicedialog Example
Figure 9.4 A single choice dialog

centre option does not work on Windows operating systems, and neither does the pos argument.

If you want to set the dialog default before the user sees it, use the method SetSelection(selection). The argument to that method is the integer index of the selection, and not the actual string to be selected. After the user has made a selection, you can retrieve it by using either GetSelection(), which returns the integer index of the selected option, or GetStringSelection() which returns the actual selected string.

There are two convenience functions for single choice dialogs. The first, wx.GetSingleChoice, returns the string that the user selected.

wx.GetSingleChoice(message, caption, aChoices, parent=None)

The message, caption, and parent arguments are as in the wx.SingleChoiceDialog constructor. The aChoices argument is the list of items. The return value is the selected string if the user presses OK, and the empty string if the user presses Cancel. This means that if the empty string is a valid choice, you should probably not use this function.

Instead, you might use wx.GetSingleChoiceindex.

wx.GetSingleChoiceindex(message, caption, aChoices, parent=None)

This function has the same arguments, but a different return value. It returns the index of the user choice if OK, and -1 if the user hits Cancel.

Was this article helpful?

+1 -1

Responses

  • martino
    How to print multiple single choice dialogs at the same time wxpython?
    8 years ago
  • yorda
    How to display wx choice?
    4 years ago

Post a comment