The last dialog we are going to examine in this article is the wxFileDialog. It allows the user to save or open a file. Setting up a basic dialog is pretty simple. Let's set up one that allows the user to select a file to open: from wxPython.wx import * application = wxPySimpleApp() # Create an open file dialog dialog = wxFileDialog ( None, style = wxOPEN ) # Show the dialog and get user input if dialog.ShowModal() == wxID_OK: print 'Selected:', dialog.GetPath() # The user did not select anything else: print 'Nothing was selected.' # Destroy the dialog dialog.Destroy() Let's make our dialog more complicated. First, let's create some filters so the user can select a file type from a list. Second, let's display a message on the dialog. Third, let's allow multiple files to be selected: from wxPython.wx import * application = wxPySimpleApp() # Create a list of filters # This should be fairly simple to follow, so no explanation is necessary filters = 'All files (*.*)|*.*|Text files (*.txt)|*.txt' dialog = wxFileDialog ( None, message = 'Open something....', wildcard = filters, style = wxOPEN | wxMULTIPLE ) if dialog.ShowModal() == wxID_OK: # We'll have to make room for multiple files here selected = dialog.GetPaths() for selection in selected: print 'Selected:', selection else: print 'Nothing was selected.' dialog.Destroy() Now let's create a dialog that allows us to save files. This is done by simply changing the style wxOPEN to wxSAVE: from wxPython.wx import * application = wxPySimpleApp() # Create a save file dialog dialog = wxFileDialog ( None, style = wxSAVE ) # Show the dialog and get user input if dialog.ShowModal() == wxID_OK: print 'Selected:', dialog.GetPath() # The user did not select anything else: print 'Nothing was selected.' # Destroy the dialog dialog.Destroy() A lot of applications present the user with a confirmation dialog if he or she selects a file that already exists. This can be accomplished in your own application by using wxOVERWRITE_PROMPT: from wxPython.wx import * application = wxPySimpleApp() # Create a save file dialog dialog = wxFileDialog ( None, style = wxSAVE | wxOVERWRITE_PROMPT ) # Show the dialog and get user input if dialog.ShowModal() == wxID_OK: print 'Selected:', dialog.GetPath() # The user did not select anything else: print 'Nothing was selected.' # Destroy the dialog dialog.Destroy() Conclusion We've looked at a variety of dialogs that wxPython provides. Dialogs allow programmers to implement common features in their applications without doing much work at all. Instead of working with complex controls to do a simple task, a programmer can call a few methods and have it all done for him or her. All dialogs are simple to create and manage, as this article has thrown through examples. They are worth using in many wxPython applications – both large and small.
blog comments powered by Disqus |
|
|
|
|
|
|
|