wxPython - Dialog Class


Advertisements

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 −

S.N. Parameters & Description
1

wx.CAPTION

Puts a caption on the dialog box

2

wx.DEFAULT_DIALOG_STYLE

Equivalent to a combination of wxCAPTION, wxCLOSE_BOX and wxSYSTEM_MENU

3

wx.RESIZE_BORDER

Displays a resizable frame around the window

4

wxSYSTEM_MENU

Displays a system menu

5

wx.CLOSE_BOX

Displays a close box on the frame

6

wx.MAXIMIZE_BOX

Displays a maximize box on the dialog

7

wx.MINIMIZE_BOX

Displays a minimize box on the dialog

8

wx.STAY_ON_TOP

Ensures the dialog stays on top of all other windows

9

wx.DIALOG_NO_PARENT

Prevents creating orphan dialog. Not recommended for modal dialogs

Two even binders are defined for this class −

S.N. Events & Description
1

EVT_CLOSE

When the dialog is being closed by the user or programmatically

2

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.

S.N. Methods & Description
1

DoOK()

Called when OK button on the dialog is pressed

2

ShowModal()

Shows the dialog in application modal fashion

3

ShowWindowModal()

Dialog is modal to top level parent window only

4

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.

S.N. Buttons & Description
1

wx.OK

Shows OK button

2

wx.CANCEL

Shows Cancel button

3

wx.YES_NO

Shows Yes, No buttons

4

wx.YES_DEFAULT

Makes Yes button as default

5

wx.NO_DEFAULT

Makes No button as default

6

wx.ICON_EXCLAMATION

Shows an alert icon

7

wx.ICON_ERROR

Shows an error icon

8

wx.ICON_HAND

Same as wx.ICON_ERROR

9

wx.ICON_INFORMATION

Show an info icon

10

wx.ICON_QUESTION

Shows a question icon

MessageDialog

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.

Example

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 −

Message Dialog Output

wx.TextEntryDialog

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 −

S.N. Methods & Description
1

SetMaxLength()

Sets the maximum number of characters the user can enter into the text box

2

SetValue()

Sets the text box value programmatically

3

GetValue()

Returns the contents of the text box

4

ShowModal()

Shows dialog modally. Returns wx.ID_OK if the user confirms input, and wx.ID_CANCEL if the dialog is rejected

Example

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 −

Text Entry Output

wx.FileDialog Class

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 −

S.N. Parameters & Description
1

wx.FD_DEFAULT_STYLE

Equivalent to wxFD_OPEN

2

wx.FD_OPEN

This is an open dialog; default button's label of the dialog is "Open"

3

wx.FD_SAVE

This is a save dialog; default button's label of the dialog is "Save"

4

wx.FD_OVERWRITE_PROMPT

For save dialog only: prompts for a confirmation if a file will be overwritten

5

wx.FD_MULTIPLE

For open dialog only: allows selecting multiple files

6

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 −

S.N. Functions & Description
1

GetDirectory()

Returns default directory

2

GetFileName()

Returns default file name

3

GetPath()

Returns full path of selected file

4

SetDirectory()

Sets default directory

5

SetFilename()

Sets default file

6

SetPath()

Sets full path

7

ShowModal()

Displays dialog, returns wx.ID_OK if the user clicks OK button and wx.ID_CANCEL otherwise

Example

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 −

File Dialog Demo Choose a File File Dialog Demo Output

wx.FontDialog Class

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 −

Font Dialog Demo Output
wxpython_major_classes.htm
Advertisements