python wx.TextCtrl 和 wx.Validator
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2198903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
wx.TextCtrl and wx.Validator
提问by RSK
I need to validate the textboxes with wx.Textvalidator. Any please help me to do this?
我需要使用 wx.Textvalidator 验证文本框。任何请帮我做到这一点?
How can i use wx.FILTER_ALPHA with validators and if the user is giving a wrong input how can i give them a message?
我如何将 wx.FILTER_ALPHA 与验证器一起使用,如果用户输入错误,我该如何向他们发送消息?
i need to validate all the inputs when clicking on the save button?
单击保存按钮时,我需要验证所有输入吗?
can any one provide me a sample code for this?
任何人都可以为此提供示例代码吗?
采纳答案by Steven Sproat
This is a feature of wxWidgets, and is not implemented in wxPython.
这是 wxWidgets 的一个特性,在 wxPython 中没有实现。
http://www.wxpython.org/docs/api/wx.TextValidator-class.html- not found
http://www.wxpython.org/docs/api/wx.TextValidator-class.html- 未找到
while:
尽管:
http://docs.wxwidgets.org/trunk/classwx_text_validator.htmlhttp://docs.wxwidgets.org/stable/wx_wxtextvalidator.html
http://docs.wxwidgets.org/trunk/classwx_text_validator.html http://docs.wxwidgets.org/stable/wx_wxtextvalidator.html
There is a demo of the Validators in the wxPython demo:
wxPython 演示中有验证器的演示:
import wx
class TextObjectValidator(wx.PyValidator):
""" This validator is used to ensure that the user has entered something
into the text object editor dialog's text field.
"""
def __init__(self):
""" Standard constructor.
"""
wx.PyValidator.__init__(self)
def Clone(self):
""" Standard cloner.
Note that every validator must implement the Clone() method.
"""
return TextObjectValidator()
def Validate(self, win):
""" Validate the contents of the given text control.
"""
textCtrl = self.GetWindow()
text = textCtrl.GetValue()
if len(text) == 0:
wx.MessageBox("A text object must contain some text!", "Error")
textCtrl.SetBackgroundColour("pink")
textCtrl.SetFocus()
textCtrl.Refresh()
return False
else:
textCtrl.SetBackgroundColour(
wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
textCtrl.Refresh()
return True
def TransferToWindow(self):
""" Transfer data from validator to window.
The default implementation returns False, indicating that an error
occurred. We simply return True, as we don't do any data transfer.
"""
return True # Prevent wxDialog from complaining.
def TransferFromWindow(self):
""" Transfer data from window to validator.
The default implementation returns False, indicating that an error
occurred. We simply return True, as we don't do any data transfer.
"""
return True # Prevent wxDialog from complaining.
#----------------------------------------------------------------------
class TestValidateDialog(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, -1, "Validated Dialog")
self.SetAutoLayout(True)
VSPACE = 10
fgs = wx.FlexGridSizer(0, 2)
fgs.Add((1,1));
fgs.Add(wx.StaticText(self, -1,
"These controls must have text entered into them. Each\n"
"one has a validator that is checked when the Okay\n"
"button is clicked."))
fgs.Add((1,VSPACE)); fgs.Add((1,VSPACE))
label = wx.StaticText(self, -1, "First: ")
fgs.Add(label, 0, wx.ALIGN_RIGHT|wx.CENTER)
fgs.Add(wx.TextCtrl(self, -1, "", validator = TextObjectValidator()))
fgs.Add((1,VSPACE)); fgs.Add((1,VSPACE))
label = wx.StaticText(self, -1, "Second: ")
fgs.Add(label, 0, wx.ALIGN_RIGHT|wx.CENTER)
fgs.Add(wx.TextCtrl(self, -1, "", validator = TextObjectValidator()))
buttons = wx.StdDialogButtonSizer() #wx.BoxSizer(wx.HORIZONTAL)
b = wx.Button(self, wx.ID_OK, "OK")
b.SetDefault()
buttons.AddButton(b)
buttons.AddButton(wx.Button(self, wx.ID_CANCEL, "Cancel"))
buttons.Realize()
border = wx.BoxSizer(wx.VERTICAL)
border.Add(fgs, 1, wx.GROW|wx.ALL, 25)
border.Add(buttons)
self.SetSizer(border)
border.Fit(self)
self.Layout()
app = wx.App(redirect=False)
f = wx.Frame(parent=None)
f.Show()
dlg = TestValidateDialog(f)
dlg.ShowModal()
dlg.Destroy()
app.MainLoop()
回答by Mike Driscoll
There are lots of ways to do this. The wxPython demo actually shows how to allow only digits or only alpha. Here's an example based on that:
有很多方法可以做到这一点。wxPython 演示实际上展示了如何只允许数字或只允许字母。这是一个基于此的示例:
import wx
import string
########################################################################
class CharValidator(wx.PyValidator):
''' Validates data as it is entered into the text controls. '''
#----------------------------------------------------------------------
def __init__(self, flag):
wx.PyValidator.__init__(self)
self.flag = flag
self.Bind(wx.EVT_CHAR, self.OnChar)
#----------------------------------------------------------------------
def Clone(self):
'''Required Validator method'''
return CharValidator(self.flag)
#----------------------------------------------------------------------
def Validate(self, win):
return True
#----------------------------------------------------------------------
def TransferToWindow(self):
return True
#----------------------------------------------------------------------
def TransferFromWindow(self):
return True
#----------------------------------------------------------------------
def OnChar(self, event):
keycode = int(event.GetKeyCode())
if keycode < 256:
#print keycode
key = chr(keycode)
#print key
if self.flag == 'no-alpha' and key in string.letters:
return
if self.flag == 'no-digit' and key in string.digits:
return
event.Skip()
########################################################################
class ValidationDemo(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, wx.ID_ANY,
"Text Validation Tutorial")
panel = wx.Panel(self)
textOne = wx.TextCtrl(panel, validator=CharValidator('no-alpha'))
textTwo = wx.TextCtrl(panel, validator=CharValidator('no-digit'))
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(textOne, 0, wx.ALL, 5)
sizer.Add(textTwo, 0, wx.ALL, 5)
panel.SetSizer(sizer)
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = ValidationDemo()
frame.Show()
app.MainLoop()
An alternative approach would be to use Masked controls using wx.lib.masked. The wxPython demo has examples of this as well.
另一种方法是使用 wx.lib.masked 使用 Masked 控件。wxPython 演示也有这方面的例子。
回答by Luke Tunmer
The problem is probably thast you have the ctrl in a panel within the dialog. Set the recursive flag on the dialog to enable validation code to look for controls with validators recursively:
问题可能是您在对话框的面板中使用了 ctrl。在对话框上设置递归标志以启用验证代码以递归方式查找带有验证器的控件:
self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)
回答by David L Ernstrom
I was unable to make the sample code work properly within my code (not using a dialog at all but a txtctrl within a panel), even though it works correctly in the demo (go figure).
我无法使示例代码在我的代码中正常工作(根本不使用对话框,而是在面板中使用 txtctrl),即使它在演示中正常工作(见图)。
I ended up using a snippet from another site and feel obligated to document it here:
我最终使用了另一个网站的片段,并觉得有义务在此处记录它:
self.tc.GetValidator().Validate(self.tc)
This was the only way that I could get my custom validator code to be called. Calling self.tc.Validate() did not work at all nor did self.Validate(), nor either representation passing the window in as a parameter.
这是我可以调用自定义验证器代码的唯一方法。调用 self.tc.Validate() 根本不起作用,self.Validate() 也不起作用,也没有将窗口作为参数传递的表示。
reference: link text
参考:链接文本