wxPython - Dialog Class

Although a Dialog class object appears like a Frame, it is normally used as a pop-up window on top of a parent frame. The objective of a Dialog is to collect some data from the user and send it to the parent frame. Dialog frame can be modal (where it blocks the parent frame) or modeless (dialog frame can be bypassed). ShowModal() method displays dialog frame in the modal manner, while Show() makes it modeless.
wxPython has a number of preconfigured Dialog widgets such as MessageDialog, FileDialog, FontDialog, etc.
wx.Dialog supports the use of Sizers just as a wx.Frame object. Hence, a custom Dialog can be designed.
Wx.Dialog class constructor takes the following usual parameters −
wx.Dialog(parent, id, title, pos, size, style)

Default appearance of Dialog widget shows only Close box in the title bar. However, it can be customized using a combination of the following style parameters −
wx.CAPTION
Puts a caption on the dialog box
wx.DEFAULT_DIALOG_STYLE
Equivalent to a combination of wxCAPTION, wxCLOSE_BOX and wxSYSTEM_MENU
wx.RESIZE_BORDER
Displays a resizable frame around the window
wxSYSTEM_MENU
Displays a system menu
wx.CLOSE_BOX
Displays a close box on the frame
wx.MAXIMIZE_BOX
Displays a maximize box on the dialog
wx.MINIMIZE_BOX
Displays a minimize box on the dialog
wx.STAY_ON_TOP
Ensures the dialog stays on top of all other windows
wx.DIALOG_NO_PARENT
Prevents creating orphan dialog. Not recommended for modal dialogs
Two even binders are defined for this class −
EVT_CLOSE
When the dialog is being closed by the user or programmatically
EVT_INIT_DIALOG
When the dialog is being initialized
As mentioned above, the objective of Dialog is to collect data and return to the parent window. However, some useful methods are available for Dialog class.
DoOK()
Called when OK button on the dialog is pressed
ShowModal()
Shows the dialog in application modal fashion
ShowWindowModal()
Dialog is modal to top level parent window only
EndModal()
Ends a modal dialog passing the value from ShowModal invocation
One of the preconfigured dialogs is MessageDialog. It is used to display a message of one or more lines with buttons having standard IDs. Here is a select list of standard buttons on MessageDialog.
wx.OK
Shows OK button
wx.CANCEL
Shows Cancel button
wx.YES_NO
Shows Yes, No buttons
wx.YES_DEFAULT
Makes Yes button as default
wx.NO_DEFAULT
Makes No button as default
wx.ICON_EXCLAMATION
Shows an alert icon
wx.ICON_ERROR
Shows an error icon
wx.ICON_HAND
Same as wx.ICON_ERROR
wx.ICON_INFORMATION
Show an info icon
wx.ICON_QUESTION
Shows a question icon
This is declared with the following constructor −
wx.MessageDialog(parent, message, caption, style, pos)

One or more lines of the text to be displayed is the message parameter, while the caption is displayed on the title bar. Default style parameter is wx.OK|wx.ECNRE. Other style parameters allow the message box to be customized.
wx.MessageBox is a convenience function to construct a message box instead of using MessageDialog.
Given below is a simple demonstration of modal and modeless behavior of Dialog. The parent window is a wx.Frame object with two buttons. Click event on the first button displays a dialog in modal fashion. Hence, any operation on the parent window is prevented till the dialog is closed. The second button displays a modeless dialog, which doesn’t obstruct access to parent window. The third button displays a MessageBox.
The entire code is as follows −
import wx
  
class MyDialog(wx.Dialog): 
   def __init__(self, parent, title): 
      super(MyDialog, self).__init__(parent, title = title, size = (250,150)) 
      panel = wx.Panel(self) 
      self.btn = wx.Button(panel, wx.ID_OK, label = "ok", size = (50,20), pos = (75,50))
		
class Mywin(wx.Frame): 
            
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title, size = (250,150))  
      self.InitUI() 
         
   def InitUI(self):    
      panel = wx.Panel(self) 
      btn = wx.Button(panel, label = "Modal Dialog", pos = (75,10)) 
      btn1 = wx.Button(panel, label = "Modeless Dialog", pos = (75,40)) 
      btn2 = wx.Button(panel, label = "MessageBox", pos = (75,70)) 
      btn.Bind(wx.EVT_BUTTON, self.OnModal)
		
      a = btn1.Bind(wx.EVT_BUTTON, self.OnModeless) 
      print a 
      btn2.Bind(wx.EVT_BUTTON, self.Onmsgbox) 
      self.Centre() 
      self.Show(True) 
		
   def OnModal(self, event): 
      a = MyDialog(self, "Dialog").ShowModal() 
      print a 
		
   def OnModeless(self, event): 
      a = MyDialog(self, "Dialog").Show()
		
   def Onmsgbox(self, event): 
      wx.MessageBox("This is a Message Box", "Message" ,wx.OK | wx.ICON_INFORMATION)  
		
ex  =  wx.App() 
Mywin(None,'MenuBar demo') 
ex.MainLoop()
The above code produces the following output −
Object of this class displays a dialog with one text field, a customizable label prompting the user to input and two buttons with predefined styles.
Although this dialog requests a one line input, the text box can be customized by using TextCtrl styles like password and multiline.
Contents of the text field are collected as return value when the user clicks OK button.
TextEntryDialog constructor is as follows −
wx.TextEntryDialog(parent, id, message, caption, value, style, pos)

The text to be displayed on the Dialog window is passed as the message parameter. The caption parameter is the string to be displayed in the title bar. Default string in the text box is vthe alue parameter. TextCtrl in dialog can be configured to display password characters (wx.TE_PASSWORD) and/or multiline (wx.TE_MULTILINE).
Other methods of TextEntry class are as listed in the following table −
SetMaxLength()
Sets the maximum number of characters the user can enter into the text box
SetValue()
Sets the text box value programmatically
GetValue()
Returns the contents of the text box
ShowModal()
Shows dialog modally. Returns wx.ID_OK if the user confirms input, and wx.ID_CANCEL if the dialog is rejected
Top level frame in the following example shows a button and a read-only TextCtrl widget.
self.text = wx.TextCtrl(pnl, size = (250, 25),style = wx.TE_READONLY) 
self.btn1 = wx.Button(pnl, label = "Enter Text")

The button responds to click and invokes the OnClick() function.
self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1)

OnClick() function displays a TextEntryDialog.
dlg = wx.TextEntryDialog(self, 'Enter Your Name','Text Entry Dialog')

Return value of the dialog is fetched by GetValue() function and displayed in the TextCtrl object of top level frame.
if dlg.ShowModal() == wx.ID_OK: 
   self.text.SetValue("Name entered:"+dlg.GetValue())
The complete code is as follows −
import wx 
 
class Mywin(wx.Frame): 
            
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title,size = (300,200))  
         
      self.InitUI() 
         
   def InitUI(self):    
      self.count = 0 
      pnl = wx.Panel(self) 
      vbox = wx.BoxSizer(wx.VERTICAL) 
		
      hbox1 = wx.BoxSizer(wx.HORIZONTAL) 
      hbox2 = wx.BoxSizer(wx.HORIZONTAL) 
		
      self.text = wx.TextCtrl(pnl, size = (250, 25),style = wx.TE_READONLY) 
      self.btn1 = wx.Button(pnl, label = "Enter Text") 
      self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) 
		
      hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) 
      hbox2.Add(self.btn1, proportion = 1, flag = wx.RIGHT, border = 10)
		
      vbox.Add((0, 30)) 
      vbox.Add(hbox1, flag = wx.ALIGN_CENTRE) 
      vbox.Add((0, 20)) 
      vbox.Add(hbox2, proportion = 1, flag = wx.ALIGN_CENTRE) 
		
      pnl.SetSizer(vbox) 
      self.Centre() 
      self.Show(True)
		
   def OnClick(self, e): 
      dlg = wx.TextEntryDialog(self, 'Enter Your Name','Text Entry Dialog') 
		
      if dlg.ShowModal() == wx.ID_OK: 
         self.text.SetValue("Name entered:"+dlg.GetValue()) 
      dlg.Destroy() 
                                    
ex = wx.App() 
Mywin(None,'TextEntry Demo') 
ex.MainLoop()
The above code produces the following output −
This class represents a file selector dialog. It enables the user to navigate through the file system and select a file to open or save. Appearance of the dialog is OS specific.
A file filter can also be applied to display the files of specified extensions only.  Starting directory and default file name can also be set.
FileDialog constructor’s prototype looks like this −
wx.FileDialog(parent, message, DefaultDir, DefaultFile, wildcard, style, pos, size)

The message represents text to be displayed. DefaultDir is the initial directory. One or more types of files can be set as file filter represented by wildcard parameter.
Style parameters defined for FileDialog are −
wx.FD_DEFAULT_STYLE
Equivalent to wxFD_OPEN
wx.FD_OPEN
This is an open dialog; default button's label of the dialog is "Open"
wx.FD_SAVE
This is a save dialog; default button's label of the dialog is "Save"
wx.FD_OVERWRITE_PROMPT
For save dialog only: prompts for a confirmation if a file will be overwritten
wx.FD_MULTIPLE
For open dialog only: allows selecting multiple files
wx.FD_CHANGE_DIR
Changes the current working directory to the directory where the file(s) chosen by the user are
Member functions of wx.FileDialog class −
GetDirectory()
Returns default directory
GetFileName()
Returns default file name
GetPath()
Returns full path of selected file
SetDirectory()
Sets default directory
SetFilename()
Sets default file
SetPath()
Sets full path
ShowModal()
Displays dialog, returns wx.ID_OK if the user clicks OK button and wx.ID_CANCEL otherwise
In the following example, the top level frame shows a button and a multiline TextCtrl.
self.text = wx.TextCtrl(pnl, size = (-1,200), style = wx.TE_MULTILINE) 
self.btn1 = wx.Button(pnl, label = "Open a File")

EVT_BUTTON event binder registers OnClick() function with the button.
self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1)

OnClick() function displays a FileDialog in open mode. Its selection is returned as dlg. The selected file is obtained by GetPath() function and its contents are displayed in TextCtrl box on parent window.
def OnClick(self, e): 
   wildcard = "Text Files (*.txt)|*.txt" 
   dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN) 
	
   if dlg.ShowModal() == wx.ID_OK:
      f = open(dlg.GetPath(), 'r') 
      with f: 
         data = f.read() 
         self.text.SetValue(data) 
The complete code is as follows −
import wx 
import os 

class Mywin(wx.Frame): 
            
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title)  
         
      self.InitUI() 
         
   def InitUI(self):    
      self.count = 0 
      pnl = wx.Panel(self) 
      vbox = wx.BoxSizer(wx.VERTICAL) 
      hbox1 = wx.BoxSizer(wx.HORIZONTAL) 
      hbox2 = wx.BoxSizer(wx.HORIZONTAL) 
		
      self.text = wx.TextCtrl(pnl, size = (-1,200),style = wx.TE_MULTILINE) 
      self.btn1 = wx.Button(pnl, label = "Open a File") 
      self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) 
		
      hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) 
      hbox2.Add(self.btn1, proportion = 1, flag = wx.RIGHT, border = 10) 
		
      vbox.Add(hbox2, proportion = 1, flag = wx.ALIGN_CENTRE) 
         
      vbox.Add(hbox1, proportion = 1, flag = wx.EXPAND|wx.ALIGN_CENTRE) 
         
      pnl.SetSizer(vbox) 
      self.Centre() 
      self.Show(True)   
		
   def OnClick(self, e): 
      wildcard = "Text Files (*.txt)|*.txt" 
      dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.OPEN)
		
      if dlg.ShowModal() == wx.ID_OK: 
         f = open(dlg.GetPath(), 'r') 
			
         with f: 
            data = f.read() 
            self.text.SetValue(data)  
      dlg.Destroy() 
                                    
ex = wx.App() 
Mywin(None, 'FileDialog Demo') 
ex.MainLoop()
The above code produces the following output −
The object of this class is a font chooser dialog. Appearance of this dialog too is OS specific. Attributes, such as name, size, weight, etc. of the selected font are returned as the return value of this dialog.
Fontdata parameter required for this class constructor is used to initialize these attributes.
wx.FontDialog(parent, data)

GetFontData() method of this class contains the parameters of the selected font.
The following code demonstrating the use of FontDialog has a button and a label (StaticText object).
self.text = wx.StaticText(pnl, label = "hello") 
self.btn1 = wx.Button(pnl, label = "Choose Font")

The button when clicked triggers OnClick() event handler function.
def OnClick(self, e): 
   dlg = wx.FontDialog(self,wx.FontData()) 
	
   if dlg.ShowModal() == wx.ID_OK: 
      data = dlg.GetFontData() 
      font = data.GetChosenFont() 
      self.text.SetFont(font) 
		
   dlg.Destroy()
The chosen font is then applied to label’s text.
The complete code is as follows −
import wx 
import os 

class Mywin(wx.Frame): 
            
   def __init__(self, parent, title): 
      super(Mywin, self).__init__(parent, title = title, size = (250,200))  
         
      self.InitUI() 
         
   def InitUI(self):    
      self.count = 0 
      pnl = wx.Panel(self) 
		
      vbox = wx.BoxSizer(wx.VERTICAL) 
      hbox1 = wx.BoxSizer(wx.HORIZONTAL) 
      hbox2 = wx.BoxSizer(wx.HORIZONTAL)
		
      self.text = wx.StaticText(pnl, label = "hello") 
      self.btn1 = wx.Button(pnl, label = "Choose Font")
      self.Bind(wx.EVT_BUTTON, self.OnClick, self.btn1) 
		
      hbox1.Add(self.text, proportion = 1, flag = wx.ALIGN_CENTRE) 
      hbox2.Add(self.btn1, proportion = 1, flag = wx.ALIGN_CENTRE, border = 10) 
		
      vbox.Add(hbox2, flag = wx.ALIGN_CENTRE) 
         
      vbox.Add(hbox1, proportion = 1, flag = wx.ALIGN_CENTRE) 
         
      pnl.SetSizer(vbox) 
      self.Centre() 
      self.Show(True) 
      
   def OnClick(self, e): 
      dlg = wx.FontDialog(self,wx.FontData()) 
		
      if dlg.ShowModal() == wx.ID_OK: 
         data = dlg.GetFontData() 
         font = data.GetChosenFont() 
         self.text.SetFont(font)
			
      dlg.Destroy() 
		
ex = wx.App() 
Mywin(None,'FileDialog Demo') 
ex.MainLoop()
The above code produces the following output −
 Print
 Add Notes
 Bookmark this page