wx.TextCtrl和wx.Validator

时间:2010-02-04 10:30:27

标签: python wxpython

我需要使用wx.Textvalidator验证文本框。 请帮帮我这个吗?

如何将wx.FILTER_ALPHA与验证器一起使用,如果用户输错了,我该如何给他们留言?

我需要在点击保存按钮时验证所有输入吗?

任何人都可以为我提供一个示例代码吗?

4 个答案:

答案 0 :(得分:5)

这是wxWidgets的一个功能,在wxPython中没有实现。

http://www.wxpython.org/docs/api/wx.TextValidator-class.html - 未找到

,同时:

http://docs.wxwidgets.org/trunk/classwx_text_validator.html http://docs.wxwidgets.org/stable/wx_wxtextvalidator.html

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()

答案 1 :(得分:4)

有很多方法可以做到这一点。 wxPython演示实际上演示了如何仅允许数字或仅允许alpha。以下是基于此的示例:

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()

另一种方法是使用wx.lib.masked来使用Masked控件。 wxPython演示也有这样的例子。

答案 2 :(得分:2)

问题可能是你在对话框的面板中有ctrl。在对话框上设置递归标志,以使验证代码能够递归地查找带有验证器的控件:

self.SetExtraStyle(wx.WS_EX_VALIDATE_RECURSIVELY)

答案 3 :(得分:1)

我无法在我的代码中使示例代码正常工作(除了面板中的txtctrl之外根本不使用对话框),即使它在演示中正常工作(如图)。

我最终使用了其他网站的代码段,并且有义务在此处记录:

self.tc.GetValidator().Validate(self.tc)

这是我可以调用自定义验证器代码的唯一方法。调用self.tc.Validate()根本不起作用,也没有self.Validate(),也没有将窗口作为参数传递。

参考:link text