]> git.saurik.com Git - wxWidgets.git/blob - wxPython/samples/wxPIA_book/Chapter-09/validator1.py
Added the sample code from wxPython In Action to the samples dir
[wxWidgets.git] / wxPython / samples / wxPIA_book / Chapter-09 / validator1.py
1 import wx
2
3 about_txt = """\
4 The validator used in this example will ensure that the text
5 controls are not empty when you press the Ok button, and
6 will not let you leave if any of the Validations fail."""
7
8
9 class NotEmptyValidator(wx.PyValidator):
10 def __init__(self):
11 wx.PyValidator.__init__(self)
12
13 def Clone(self):
14 """
15 Note that every validator must implement the Clone() method.
16 """
17 return NotEmptyValidator()
18
19 def Validate(self, win):
20 textCtrl = self.GetWindow()
21 text = textCtrl.GetValue()
22
23 if len(text) == 0:
24 wx.MessageBox("This field must contain some text!", "Error")
25 textCtrl.SetBackgroundColour("pink")
26 textCtrl.SetFocus()
27 textCtrl.Refresh()
28 return False
29 else:
30 textCtrl.SetBackgroundColour(
31 wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
32 textCtrl.Refresh()
33 return True
34
35 def TransferToWindow(self):
36 return True
37
38 def TransferFromWindow(self):
39 return True
40
41
42
43 class MyDialog(wx.Dialog):
44 def __init__(self):
45 wx.Dialog.__init__(self, None, -1, "Validators: validating")
46
47 # Create the text controls
48 about = wx.StaticText(self, -1, about_txt)
49 name_l = wx.StaticText(self, -1, "Name:")
50 email_l = wx.StaticText(self, -1, "Email:")
51 phone_l = wx.StaticText(self, -1, "Phone:")
52
53 name_t = wx.TextCtrl(self, validator=NotEmptyValidator())
54 email_t = wx.TextCtrl(self, validator=NotEmptyValidator())
55 phone_t = wx.TextCtrl(self, validator=NotEmptyValidator())
56
57 # Use standard button IDs
58 okay = wx.Button(self, wx.ID_OK)
59 okay.SetDefault()
60 cancel = wx.Button(self, wx.ID_CANCEL)
61
62 # Layout with sizers
63 sizer = wx.BoxSizer(wx.VERTICAL)
64 sizer.Add(about, 0, wx.ALL, 5)
65 sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
66
67 fgs = wx.FlexGridSizer(3, 2, 5, 5)
68 fgs.Add(name_l, 0, wx.ALIGN_RIGHT)
69 fgs.Add(name_t, 0, wx.EXPAND)
70 fgs.Add(email_l, 0, wx.ALIGN_RIGHT)
71 fgs.Add(email_t, 0, wx.EXPAND)
72 fgs.Add(phone_l, 0, wx.ALIGN_RIGHT)
73 fgs.Add(phone_t, 0, wx.EXPAND)
74 fgs.AddGrowableCol(1)
75 sizer.Add(fgs, 0, wx.EXPAND|wx.ALL, 5)
76
77 btns = wx.StdDialogButtonSizer()
78 btns.AddButton(okay)
79 btns.AddButton(cancel)
80 btns.Realize()
81 sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)
82
83 self.SetSizer(sizer)
84 sizer.Fit(self)
85
86
87 app = wx.PySimpleApp()
88
89 dlg = MyDialog()
90 dlg.ShowModal()
91 dlg.Destroy()
92
93 app.MainLoop()