Dialogs in wxPython (Page 1 of 6 )
You are probably already familiar with a few dialogs that can be used in your
wxPython applications. Of course,
wxPython contains many more dialogs, ranging in complexity from very simple to pretty advanced and covering a variety of topics, from text selection to color selection. In this article, we'll take a look at more of
wxPython's dialogs – what they are for and how they are placed in an application.
wxSingleChoiceDialog
Instead of using a wxListBox to gather input from a user, you can use the wxSingleChoiceDialog. Upon calling it, a dialog is displayed to the user with a list of items that the user can select. The user may only select one item on the list. At the bottom of the dialog, there is an “OK” button and a “Cancel” button. Let's create a simple application with the dialog:
from wxPython.wx import *
from wxPython.lib.dialogs import *
application = wxPySimpleApp()
# Create a list of choices
choices = [ 'Red', 'Blue', 'Green', 'Pink', 'White' ]
# Create the dialog
dialog = wxSingleChoiceDialog ( None, 'Pick something....', 'Dialog Title', choices )
# Show the dialog
dialog.ShowModal()
# Destroy the dialog
dialog.Destroy()
Of course, to make our dialog of any use, we'll have to catch the user's selection and perhaps react to the user pressing the “Cancel” button:
from wxPython.wx import *
application = wxPySimpleApp()
choices = [ 'Red', 'Blue', 'Green', 'Pink', 'White' ]
dialog = wxSingleChoiceDialog ( None, 'Pick something....', 'Dialog Title', choices )
# The user pressed the "OK" button in the dialog
if dialog.ShowModal() == wxID_OK:
print 'Position of selection:', dialog.GetSelection()
print 'Selection:', dialog.GetStringSelection()
# The user exited the dialog without pressing the "OK" button
else:
print 'You did not select anything.'
dialog.Destroy()
If we want to give the user the option of selecting multiple items by pressing the shift key while clicking a selection or holding down the mouse and moving the cursor down, we can do so with wxMultiChoiceDialog:
from wxPython.wx import *
application = wxPySimpleApp()
choices = [ 'Red', 'Blue', 'Green', 'Pink', 'White' ]
dialog = wxMultiChoiceDialog ( None, 'Pick something....', 'Dialog Title', choices )
# The user pressed the "OK" button in the dialog
if dialog.ShowModal() == wxID_OK:
selected = dialog.GetSelections()
for selection in selected:
print str ( selection ) + ': ' + choices [ selection ]
# The user exited the dialog without pressing the "OK" button
else:
print 'You did not select anything.'
dialog.Destroy()
Next: wxScrolledMessageDialog >>
More Python Articles
More By Peyton McCullough