How to create a customized password dialog (Phoenix)
Keywords : Dialog, TextCtrl, Password, CheckBox.
Contents
Demonstrating :
Tested py3.x, wx4.x and Win10.
Are you ready to use some samples ?
Test, modify, correct, complete, improve and share your discoveries !
First example
ICON file : wxwin.ico
1 # sample_one.py
2
3 import os
4 import wx
5 from wx.lib.embeddedimage import PyEmbeddedImage
6
7 # class MyFrame
8 # class MyDlgLogin
9 # class MyApp
10
11 Key_Png = PyEmbeddedImage(
12 b'iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwY'
13 b'AAAKU0lEQVRoBe2aaXBV533Gf2e5517p6mqXkARahBYDYsEglhG4SbBZHPBiJ23G6ZdMnHxI'
14 b'xp52OvnSTnA77dClkzbJmLgd4oZAxw4uocbU4NQRBBtjBAgkawEhoUW6aNGVdBfp7vec85YZ'
15 b'vR80GtJJMxfUzOSZ+c97vun3PHre9yySIoTgd1kqS63fG/gdl84CKYrCo9KxlXnFaoxvZ+Xb'
16 b'fxgNMXQ0EPuz5khyBIjxG0oIgc4j1turCvV4VHzJ5RCHap9O1Kx+KcbwOWON/1+dRf1J65XB'
17 b'lNUFRPm/uJDDw9abNUU7j9UWXWx+Pkf4TjqEGEaIgfvTj+j6E5f4YW7WzVqHtg3I/E3Z5TH6'
18 b'cCt0ZE3xKpHg78obUs9s+EpEK21MojiAWUBIXAfcPWpw8XXH3eOxxLcuJcwWIAKIJavQ4Q0l'
19 b'BVpc+YusPPMbG56LZNc/HUPPFhBifjTAiaSB2peTaDq1/MA4fM+0vzlo2TeBCL9eD+83cHhj'
20 b'6S6XxpsNT0aq1z4bIavSghAwBwAYEt4hry0AwA0DP3Jw/vv67e/FE9/stew2IPpIK3R4U2ml'
21 b'Q1Gad7/qr61+Mg5hmXgS0CW4hBeoDN9Q8d3QcWTalDWmuF84ho46+Phf9DvHo8lXL6SsK8g6'
22 b'PZIKWUnth9u/Gqqt3hWHSSAo6+KS4IZM3mkwfKWcjw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oBR4YCkCXEBKcCEnotOms/kJI8OzrbeDMbb13oMx0A0FYhaYgi4KvudAtyACkQWViYN'
51 b'BubhFXhv74HpVTt2+0GZhw/OwNRVqC4EvSELDAf0B7j7iYGvTycRU7nanhk9OhC62juXaAFa'
52 b'gHsSLgRMAFHSoF97Ch38Yv0qTVU+ePGl8ap122ZBwk/eg7lOWFkG2hoPFJaCN4A1B5cv5tsf'
53 b'dCSHA0nT/1nA3zsZN7tk2h1AAACw5aRN+gPg1yqKcvoFCQ/z8BPDELkNK8tBrfdAQT6ETAhG'
54 b'iIRUBn2Efz4SuGwJ0S77PAwMAbOLoR+agYMH6uo0ldP7np2sWS/hKYbxAYj1zsMrHhXmkjAx'
55 b'ClETTAhNuZiO2OH78EPAZaBHdjoJCIBHYiCVUnbVrI7VbH1C3mHzYLQXbC+srJPfaiIWCW+C'
56 b'0ISC3+dgZsLAO5TJaDjpB3zAOBBckr/QJE1RkJ1joqiAB0buAGNQUaNAuRumYkSmFc4cK2Rg'
57 b'1EhMzNnhqYgZHAjFRtumI63AIBAGWBIDwlZy3R4TnDDUCVoUyuuAqhxIaRCZo68ri1Pt2siZ'
58 b'3rErKVt4gUlgBhgB+oDZJTOgqSLf4zHx9YMRh7KVQEkWZGZDzxSpabja4rGujQe678O3ANeA'
59 b'Cdn3sFzNJTPgdInCnIIk7mxwVwIpYDIK3hiYFn09blr6lGlvKH4HaAPa03Wmp8WAQ6fIFUlh'
60 b'TcDMkMzSslEswILW1mxxfWy2FxgAvDJx/t8YiCXsnlOnlq1NpixNgIoUCHRUtXvSnrrlC7cD'
61 b'd4ApQLDEWvwoUQxsBxqAzEWAiixV34K3JIsl1IOehYwF74AaiwU2MIv8/gyw9AZ+/98qS6v/'
62 b'AUoSr1gPNRy7AAAAAElFTkSuQmCC')
63
64 #---------------------------------------------------------------------------
65
66 class MyFrame(wx.Frame):
67 def __init__(self):
68 wx.Frame.__init__(self, None, title=wx.GetApp().GetAppName())
69 self.SetIcon(wx.Icon('wxwin.ico'))
70
71 self._createControls()
72
73 self.CenterOnScreen()
74
75 def _createControls(self):
76 # A Statusbar in the bottom of the window
77 self.CreateStatusBar(1)
78 sMsg = 'wxPython ' + wx.version() + ' - ' + wx.GetLibraryVersionInfo().VersionString
79 self.SetStatusText(sMsg)
80
81 # Add a panel to the frame (needed under Windows to have a nice background)
82 pnl = wx.Panel(self, wx.ID_ANY)
83
84 szrMain = wx.BoxSizer(wx.VERTICAL)
85 szrMain.AddSpacer(15)
86 label = wx.StaticText(pnl, wx.ID_STATIC, 'Well done!.\nYou have successfully entered the required password.')
87 szrMain.Add(label, 0, wx.ALL, 15)
88 szrMain.AddSpacer(15)
89
90 pnl.SetSizer(szrMain)
91
92 szrMain.SetSizeHints(self)
93
94 #---------------------------------------------------------------------------
95
96 class MyDlgLogin(wx.Dialog):
97 def __init__(self, parent, password, maxAttemps):
98 wx.Dialog.__init__(self, parent, title='Restricted access')
99
100 self._iMaxAttemps = maxAttemps
101 self._iAttemps = 0
102 self._sPassword = password
103
104 self._createInterface()
105 self._txtPwd.SetFocus()
106
107 self._connectControls()
108
109 self.CenterOnParent()
110
111 def _createInterface(self):
112 szrMain = wx.BoxSizer(wx.VERTICAL)
113
114 lnszr = wx.BoxSizer(wx.HORIZONTAL)
115 bmpCtrl = wx.StaticBitmap(self, wx.ID_STATIC, Key_Png.GetBitmap())
116 lnszr.Add(bmpCtrl, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 10)
117 label = wx.StaticText(self, wx.ID_STATIC, 'Access to this application has been\nprotected with a password.')
118 lnszr.Add(label, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 10)
119 szrMain.Add(lnszr, 0, wx.ALL, 0)
120
121 label = wx.StaticText(self, wx.ID_STATIC, 'For this test application, the password is "' + self._sPassword + '"')
122 szrMain.Add(label, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, 10)
123
124 self._lblWrongPwd = wx.StaticText(self, wx.ID_STATIC, 'Incorrect password!')
125 self._lblWrongPwd.SetFont(label.GetFont().MakeBold())
126 self._lblWrongPwd.SetForegroundColour(wx.RED)
127 szrMain.Add(self._lblWrongPwd, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.ALIGN_CENTER_HORIZONTAL, 10)
128
129 lnszr = wx.BoxSizer(wx.HORIZONTAL)
130 label = wx.StaticText(self, wx.ID_STATIC, 'Enter the access password:')
131 lnszr.Add(label, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 0)
132 self._txtPwd = wx.TextCtrl(self, wx.ID_ANY, '', style=wx.TE_PASSWORD)
133 lnszr.Add(self._txtPwd, 1, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
134 szrMain.Add(lnszr, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM|wx.EXPAND, 10)
135
136 self._chkShowPwd = wx.CheckBox(self, wx.ID_ANY, 'Display password in plain text')
137 szrMain.Add(self._chkShowPwd, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, 10)
138
139 btnSzr = self.CreateSeparatedButtonSizer(wx.OK|wx.CANCEL)
140 btnOk = self.FindWindowById(wx.ID_OK)
141 if not btnOk is None:
142 btnOk.SetLabel('Access')
143 btnOk.SetDefault()
144 szrMain.Add(btnSzr, 0, wx.ALL|wx.EXPAND, 10)
145
146 self.SetSizer(szrMain)
147
148 self._lblWrongPwd.Hide()
149
150 szrMain.SetSizeHints(self)
151
152 def _connectControls(self):
153 self._chkShowPwd.Bind(wx.EVT_CHECKBOX, self._onChkShowPasswordClicked)
154 self.Bind(wx.EVT_BUTTON, self._onBtnOkClicked, id=wx.ID_OK)
155
156 def _onChkShowPasswordClicked(self, evt):
157 self.Freeze()
158
159 sPass = self._txtPwd.GetValue()
160 lnszr = self._txtPwd.GetContainingSizer()
161 iStyle = 0
162 if not self._chkShowPwd.IsChecked():
163 iStyle = wx.TE_PASSWORD
164
165 lnszr.Detach(self._txtPwd)
166 self._txtPwd.Destroy()
167 self._txtPwd = wx.TextCtrl(self, wx.ID_ANY, sPass, style=iStyle)
168 lnszr.Add(self._txtPwd, 1, wx.LEFT|wx.ALIGN_CENTER_VERTICAL, 5)
169
170 lnszr.Layout()
171
172 self.Thaw()
173
174 def _onBtnOkClicked(self, evt):
175 iRes = wx.ID_OK
176 if self._txtPwd.GetValue() != self._sPassword:
177 iRes = wx.ID_CANCEL
178
179 if (iRes == wx.ID_OK) or (self._iAttemps == (self._iMaxAttemps - 1)):
180 self.EndModal(iRes)
181
182 if self._iAttemps == 0:
183 self._lblWrongPwd.Show()
184 self.GetSizer().SetSizeHints(self)
185 self.CenterOnParent()
186
187 self._txtPwd.SetFocus()
188 self._txtPwd.SetSelection(-1, -1)
189
190 self._iAttemps += 1
191 self._lblWrongPwd.SetLabel('Incorrect password: trial {:0d}/{:0d}'.format(self._iAttemps+1, self._iMaxAttemps))
192 self.GetSizer().Layout()
193
194 #---------------------------------------------------------------------------
195
196 class MyApp(wx.App):
197 def OnInit(self):
198 print('Running wxPython ' + wx.version())
199
200 self.locale = wx.Locale(wx.LANGUAGE_ENGLISH)
201
202 # Set Current directory to the one containing this file
203 os.chdir(os.path.dirname(os.path.abspath(__file__)))
204
205 self.SetAppName('PwdProtect')
206
207 dlg = MyDlgLogin(None, 'wxWidgets', 3)
208 if dlg.ShowModal() != wx.ID_OK:
209 wx.MessageBox('You can not access to this application!', 'Password required', wx.ICON_EXCLAMATION|wx.OK|wx.CENTER)
210 return False
211 dlg.Destroy()
212
213 # Create the main window
214 frm = MyFrame()
215 self.SetTopWindow(frm)
216
217 frm.Show()
218 return True
219
220 #---------------------------------------------------------------------------
221
222 if __name__ == '__main__':
223 app = MyApp()
224 app.MainLoop()
Second example
ICON file : wxwin.ico
1 # sample_two.py
2
3 """
4
5 https://ideal-user-interface.hatenablog.com/entry/20110929/1317254204
6
7 """
8
9 import os
10 import sys
11 import wx
12
13 # class MyLoginDialog
14 # class MyFrame
15 # class MyApp
16
17 #---------------------------------------------------------------------------
18
19 class MyLoginDialog(wx.Dialog):
20 def __init__(self, *args, **kwargs):
21 super(MyLoginDialog, self).__init__(*args, **kwargs)
22
23 #------------
24
25 # Return icons folder.
26 self.icons_dir = wx.GetApp().GetIconsDir()
27
28 #------------
29
30 # Simplified init method.
31 self.SetProperties()
32 self.CreateCtrls()
33 self.DoLayout()
34
35 #-----------------------------------------------------------------------
36
37 def SetProperties(self):
38 """
39 ...
40 """
41
42 frameIcon = wx.Icon(os.path.join(self.icons_dir,
43 "wxwin.ico"),
44 type=wx.BITMAP_TYPE_ICO)
45 self.SetIcon(frameIcon)
46 self.SetTitle("Login")
47
48
49 def CreateCtrls(self):
50 """
51 ...
52 """
53
54 font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
55 font.SetWeight(wx.BOLD)
56
57 #------------
58
59 self.pnl = wx.Panel(self)
60
61 #------------
62
63 self.username = wx.TextCtrl(self.pnl)
64 self.passwd = wx.TextCtrl(self.pnl)
65
66 self.userTxt = wx.StaticText(self.pnl, label="Username :")
67 self.userTxt.SetFont(font)
68 self.pwdTxt = wx.StaticText(self.pnl, label="Password :")
69 self.pwdTxt.SetFont(font)
70
71 #------------
72
73 self.btnOk = wx.Button(self.pnl, wx.ID_OK)
74 self.btnOk.SetDefault()
75
76 self.btnCancel = wx.Button(self.pnl, wx.ID_CANCEL)
77
78
79 def DoLayout(self):
80 """
81 ...
82 """
83
84 sizer = wx.FlexGridSizer(2, 2, 8, 8)
85 sizer.Add(self.userTxt,
86 0, wx.ALIGN_CENTER_VERTICAL)
87 sizer.Add(self.username, 0, wx.EXPAND)
88 sizer.Add(self.pwdTxt,
89 0, wx.ALIGN_CENTER_VERTICAL)
90 sizer.Add(self.passwd, 0, wx.EXPAND)
91
92 #------------
93
94 msizer = wx.BoxSizer(wx.VERTICAL)
95 msizer.Add(sizer, 1, wx.EXPAND|wx.ALL, 20)
96
97 btnszr = wx.StdDialogButtonSizer()
98 btnszr.AddButton(self.btnOk)
99 btnszr.AddButton(self.btnCancel)
100
101 msizer.Add(btnszr, 0, wx.ALIGN_CENTER|wx.ALL, 12)
102 btnszr.Realize()
103
104 self.pnl.SetSizer(msizer)
105
106 #------------
107
108 vsizer = wx.BoxSizer(wx.VERTICAL)
109 vsizer.Add(self.pnl, 1, wx.EXPAND)
110
111 #------------
112
113 self.SetSizer(vsizer)
114 self.SetInitialSize()
115
116
117 def GetUser(self):
118 """
119 ...
120 """
121
122 return self.username.GetValue()
123
124
125 def GetPasswd(self):
126 """
127 ...
128 """
129
130 return self.passwd.GetValue()
131
132 #---------------------------------------------------------------------------
133
134 class MyFrame(wx.Frame):
135 def __init__(self, parent, id, title):
136 wx.Frame.__init__(self, parent, id, title)
137
138 #------------
139
140 # Return icons folder.
141 self.icons_dir = wx.GetApp().GetIconsDir()
142
143 #------------
144
145 # Simplified init method.
146 self.SetProperties()
147
148 #------------
149
150 self.btnClose = wx.Button(self, wx.ID_EXIT,
151 label="&Quit")
152
153 #------------
154
155 sizerMain = wx.BoxSizer(wx.VERTICAL)
156 sizerMain.Add(self.btnClose, 0, wx.EXPAND)
157
158 #------------
159
160 self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
161 self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
162
163 #-----------------------------------------------------------------------
164
165 def SetProperties(self):
166 """
167 ...
168 """
169
170 self.SetMinSize((420, 200))
171 self.SetBackgroundColour(wx.Colour("#eceade"))
172
173 #------------
174
175 frameIcon = wx.Icon(os.path.join(self.icons_dir,
176 "wxwin.ico"),
177 type=wx.BITMAP_TYPE_ICO)
178 self.SetIcon(frameIcon)
179
180
181 def OnCloseBtn(self, event):
182 """
183 ...
184 """
185
186 self.Close(True)
187
188
189 def OnCloseWindow(self, event):
190 """
191 ...
192 """
193
194 self.Destroy()
195
196 #---------------------------------------------------------------------------
197
198 class MyApp(wx.App):
199 def OnInit(self):
200
201 #------------
202
203 self.installDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
204
205 #------------
206
207 login = MyLoginDialog(None)
208 loggedIn = False
209 while not loggedIn:
210 dlg = login.ShowModal()
211 if dlg == wx.ID_OK:
212 uname = login.GetUser()
213 passwd = login.GetPasswd()
214 if (uname, passwd) == ("hoge", "hoge"):
215 loggedIn = True
216 else:
217 print("Username or password is incorrect !")
218 else:
219 self.Destroy()
220
221 self.frm = MyFrame(None, -1, 'Sample two')
222 self.frm.Show(True)
223
224 return True
225
226 #---------------------------------------------------------------------------
227
228 def GetInstallDir(self):
229 """
230 Returns the installation directory for my application.
231 """
232
233 return self.installDir
234
235
236 def GetIconsDir(self):
237 """
238 Returns the icons directory for my application.
239 """
240
241 icons_dir = os.path.join(self.installDir, "icons")
242 return icons_dir
243
244 #-------------------------------------------------------------------------------
245
246 def main():
247 app = MyApp(False)
248 app.MainLoop()
249
250 #-------------------------------------------------------------------------------
251
252 if __name__ == "__main__" :
253 main()
Download source
Additional Information
Link :
- - - - -
https://wiki.wxpython.org/TitleIndex
Thanks to
Xaviou (sample_one.py coding), Hatenablog (sample_two.py coding), the wxPython community...
About this page
Date (d/m/y) Person (bot) Comments :
25/05/18 - Ecco (Created page for wxPython Phoenix).
Comments
- blah, blah, blah....