Foros del Web » Programando para Internet » Python »

Buenas, ayuda con TextCtrl y wx.EVT_TEXT

Estas en el tema de Buenas, ayuda con TextCtrl y wx.EVT_TEXT en el foro de Python en Foros del Web. Ante todo Feliz dia a todos, me gustaria realizarle una pregunta a la comunidad de Programadores. Actualmente estoy aprendiendo a usar Python en especifico wxWidgets. ...
  #1 (permalink)  
Antiguo 31/03/2010, 23:54
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Buenas, ayuda con TextCtrl y wx.EVT_TEXT

Ante todo Feliz dia a todos, me gustaria realizarle una pregunta a la comunidad de Programadores. Actualmente estoy aprendiendo a usar Python en especifico wxWidgets. Y se me ha presentado un problema a la hora de usar algunas de sus caracteristicas. Quiero realizar una pequeña aplicacion que guarde nombre y apellido en un archivo, pero deseo realizar la validacion de tal manera que si se presiona en el teclado una tecla no admitida, el programa devuelva un mensaje de aviso diciendo que solo se admite cierto tipo de caracter. Estoy usando TextCtrl y el modulo wx.EVT_TEXT para luego usar el metodo GetKeyCode y comparar usando un IF. Para que comprendan mejor dejo el codigo. Posiblemente tenga algunos errores por otro lado y si pueden ser tan amables de señarlos para corregirlos, gracias.

Código:
#!usr/bin/python
# -*- coding: utf-8 -*

'''
Created on 31/03/2010

@author: victor
'''
import wx
class App(wx.App):
    #Declaro el constructor de la clase
    def OnInit(self):
        self.ventana= wx.Frame(parent=None, title=u'Participantes',size=(500,300), pos=(250,250))
        panel = wx.Panel(self.ventana,-1)
        
        Nombre_P = wx.StaticText(panel,-1,u'Nombre Participante', pos=(30,40))
        self.cuadro_Nombre = wx.TextCtrl(panel, -1, '', pos = (210 , 40), size = (150,-1))    
        lApellido_P= wx.StaticText(panel,-1,u'Apellido Participante', pos=(30,70))        
        self.cuadro_apellido = wx.TextCtrl(panel, -1, '', pos = (210 , 70), size = (150,-1))
        boton_aceptar= wx.Button(panel, -1, u'Aceptar', pos=(30,200))
        self.Bind(wx.EVT_BUTTON, self.OnAceptar, boton_aceptar)
        self.Bind(wx.EVT_TEXT,self.EventText,self.cuadro_Nombre)
        self.ventana.Show()
        return True
      
            
            
    def EventText(self,evt):
        KeyCode=evt.GetKeyCode(evt)
        
        if KeyCode<41 and KeyCode>90:
                dialogo = wx.MessageDialog(self.ventana, u'Tecla no valida', u'Informacion', wx.OK | wx.ICON_INFORMATION)
                dialogo.ShowModal()
                dialogo.Destroy()
                       
           
                
    def OnAceptar(self,evt):
        Nombre= self.cuadro_Nombre.GetValue()
        if Nombre == "" :
           dialogo = wx.MessageDialog(self.ventana, u'El campo Nombre esta vacio', u'Informacion', wx.OK | wx.ICON_INFORMATION)
           dialogo.ShowModal()
           dialogo.Destroy()
            
if __name__ == '__main__':
    app = App()
    app.MainLoop()
    
    pass
La aplicación se ejecuta, es decir carga la ventana y también carga el mensaje al hacer clic en aceptar. Pero en la terminal de Eclipse devuelve el siguiente error. Al presionar cualquier tecla.

Traceback (most recent call last):
File "/home/victor/workspace/ventanas ejercicio/src/validarTxtCtrl.py", line 38, in EventText
KeyCode=evt.GetKeyCode(evt)
AttributeError: 'CommandEvent' object has no attribute 'GetKeyCode'


Me he basado para desarrollar esta aplicacion, en el ejemplo TxtCtrl de la seccion "Core Windows Control" del paquete wx2.8-examples. Que copio a continuacion. Y en el ejemplo de http://sccp2009.wordpress.com/widgets para la conformacion de los objetos de la ventana usando los pixeles.

#_________________________________________________ _________________________________________
Código:
import  sys
import  wx

#---------------------------------------------------------------------------

class TestPanel(wx.Panel):
    def OnSetFocus(self, evt):
        print "OnSetFocus"
        evt.Skip()
    def OnKillFocus(self, evt):
        print "OnKillFocus"
        evt.Skip()
    def OnWindowDestroy(self, evt):
        print "OnWindowDestroy"
        evt.Skip()


    def __init__(self, parent, log):
        wx.Panel.__init__(self, parent, -1)
        self.log = log

        l1 = wx.StaticText(self, -1, "wx.TextCtrl")
        t1 = wx.TextCtrl(self, -1, "Test it out and see", size=(125, -1))
        wx.CallAfter(t1.SetInsertionPoint, 0)
        self.tc1 = t1

        self.Bind(wx.EVT_TEXT, self.EvtText, t1)
        t1.Bind(wx.EVT_CHAR, self.EvtChar)
        t1.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        t1.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        t1.Bind(wx.EVT_WINDOW_DESTROY, self.OnWindowDestroy)

        l2 = wx.StaticText(self, -1, "Password")
        t2 = wx.TextCtrl(self, -1, "", size=(125, -1), style=wx.TE_PASSWORD)
        self.Bind(wx.EVT_TEXT, self.EvtText, t2)

        l3 = wx.StaticText(self, -1, "Multi-line")
        t3 = wx.TextCtrl(self, -1,
                        "Here is a looooooooooooooong line of text set in the control.\n\n"
                        "The quick brown fox jumped over the lazy dog...",
                       size=(200, 100), style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)

        t3.SetInsertionPoint(0)
        self.Bind(wx.EVT_TEXT, self.EvtText, t3)
        self.Bind(wx.EVT_TEXT_ENTER, self.EvtTextEnter, t3)
        
        b = wx.Button(self, -1, "Test Replace")
        self.Bind(wx.EVT_BUTTON, self.OnTestReplace, b)
        b2 = wx.Button(self, -1, "Test GetSelection")
        self.Bind(wx.EVT_BUTTON, self.OnTestGetSelection, b2)
        b3 = wx.Button(self, -1, "Test WriteText")
        self.Bind(wx.EVT_BUTTON, self.OnTestWriteText, b3)
        self.tc = t3


        l4 = wx.StaticText(self, -1, "Rich Text")
        t4 = wx.TextCtrl(self, -1, "If supported by the native control, this is red, and this is a different font.",
                        size=(200, 100), style=wx.TE_MULTILINE|wx.TE_RICH2)
        t4.SetInsertionPoint(0)
        t4.SetStyle(44, 47, wx.TextAttr("RED", "YELLOW"))
        points = t4.GetFont().GetPointSize()  # get the current size
        f = wx.Font(points+3, wx.ROMAN, wx.ITALIC, wx.BOLD, True)
        t4.SetStyle(63, 77, wx.TextAttr("BLUE", wx.NullColour, f))

        l5 = wx.StaticText(self, -1, "Test Positions")
        t5 = wx.TextCtrl(self, -1, "0123456789\n" * 5, size=(200, 100),
                         style = wx.TE_MULTILINE
                         #| wx.TE_RICH
                         | wx.TE_RICH2
                         )
        t5.Bind(wx.EVT_LEFT_DOWN, self.OnT5LeftDown)
        self.t5 = t5

        space = 6
        bsizer = wx.BoxSizer(wx.VERTICAL)
        bsizer.Add(b, 0, wx.GROW|wx.ALL, space)
        bsizer.Add(b2, 0, wx.GROW|wx.ALL, space)
        bsizer.Add(b3, 0, wx.GROW|wx.ALL, space)

        sizer = wx.FlexGridSizer(cols=3, hgap=space, vgap=space)
        sizer.AddMany([ l1, t1, (0,0),
                        l2, t2, (0,0),
                        l3, t3, bsizer,
                        l4, t4, (0,0),
                        l5, t5, (0,0),
                        ])
        border = wx.BoxSizer(wx.VERTICAL)
        border.Add(sizer, 0, wx.ALL, 25)
        self.SetSizer(border)
        self.SetAutoLayout(True)


    def EvtText(self, event):
        self.log.WriteText('EvtText: %s\n' % event.GetString())

    def EvtTextEnter(self, event):
        self.log.WriteText('EvtTextEnter\n')
        event.Skip()

    def EvtChar(self, event):
        self.log.WriteText('EvtChar: %d\n' % event.GetKeyCode())
        event.Skip()


    def OnTestReplace(self, evt):
        self.tc.Replace(5, 9, "IS A")
        #self.tc.Remove(5, 9)

    def OnTestWriteText(self, evt):
        self.tc.WriteText("TEXT")

    def OnTestGetSelection(self, evt):
        start, end = self.tc.GetSelection()
        text = self.tc.GetValue()
        if wx.Platform == "__WXMSW__":  # This is why GetStringSelection was added
            text = text.replace('\n', '\r\n')

        self.log.write("multi-line GetSelection(): (%d, %d)\n"
                       "\tGetStringSelection(): %s\n"
                       "\tSelectedText: %s\n" %
                       (start, end,
                        self.tc.GetStringSelection(),
                        repr(text[start:end])))

        start, end = self.tc1.GetSelection()
        text = self.tc1.GetValue()

        if wx.Platform == "__WXMSW__":  # This is why GetStringSelection was added
            text = text.replace('\n', '\r\n')

        self.log.write("single-line GetSelection(): (%d, %d)\n"
                       "\tGetStringSelection(): %s\n"
                       "\tSelectedText: %s\n" %
                       (start, end,
                        self.tc1.GetStringSelection(),
                        repr(text[start:end])))


    def OnT5LeftDown(self, evt):
        evt.Skip()
        wx.CallAfter(self.LogT5Position, evt)

    def LogT5Position(self, evt):
        text = self.t5.GetValue()
        ip = self.t5.GetInsertionPoint()
        lp = self.t5.GetLastPosition()
        self.log.write("LogT5Position:\n"
                       "\tGetInsertionPoint:\t%d\n"
                       "\ttext[insertionpoint]:\t%s\n"
                       "\tGetLastPosition:\t%d\n"
                       "\tlen(text):\t\t%d\n"
                       % (ip, text[ip], lp, len(text)))


#---------------------------------------------------------------------------

def runTest(frame, nb, log):
    win = TestPanel(nb, log)
    return win

#---------------------------------------------------------------------------


overview = """\
A TextCtrl allows text to be displayed and (possibly) edited. It may be single 
line or multi-line, support styles or not, be read-only or not, and even supports
text masking for such things as passwords.


"""


if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
#___________________________

Sin más que agregar y agradeciendo su colaboracion.

Última edición por SamuraiBlanco; 01/04/2010 a las 06:35
  #2 (permalink)  
Antiguo 01/04/2010, 13:18
Avatar de razpeitia
Moderador
 
Fecha de Ingreso: marzo-2005
Ubicación: Monterrey, México
Mensajes: 7.321
Antigüedad: 19 años, 1 mes
Puntos: 1360
Respuesta: Buenas, ayuda con TextCtrl y wx.EVT_TEXT

No es necesario que vayas validando cada vez que presiones una tecla para ver si el usuario inserto algo no deseado.

Para eso puedes usar expresiones regulares.
  #3 (permalink)  
Antiguo 01/04/2010, 18:31
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Respuesta: Buenas, ayuda con TextCtrl y wx.EVT_TEXT

gracias por contestar razpetia, voy a investigar acerca de las expresiones regulares.


______________________

Ya lei, esa solucion me parece viable. Voy a arreglar mi programita y te cuento como me fue.

Última edición por SamuraiBlanco; 01/04/2010 a las 18:35 Razón: info adiciona
  #4 (permalink)  
Antiguo 03/04/2010, 13:30
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Validar con Expresiones Regulares

ERROR, no funciono. No se obtiene el comportamiento deseado. Ayuda porfa :S

Código:
if Nombre=="" or re.match("[a-zA-Z]",u'Nombre') :
            
            dialogo = wx.MessageDialog(self.ventana, u'El campo Nombre esta vacio o se introdujo un caracter no valido', u'Informacion', wx.OK | wx.ICON_INFORMATION)
            dialogo.ShowModal()
            dialogo.Destroy()
            self.cuadro_Nombre.SetFocus()

Última edición por SamuraiBlanco; 03/04/2010 a las 17:09
  #5 (permalink)  
Antiguo 05/04/2010, 11:18
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Buenas, ayuda con TextCtrl y wx.EVT_TEXT

La forma en que llamas a "match" indica que es True si el nombre contiene una letra (no si contiene algo que no sea una letra). Además, estás comprobando siempre contra la cadena "Nombre", deberías poner allí la variable que contiene el nombre.


Saludos.
  #6 (permalink)  
Antiguo 07/04/2010, 09:57
 
Fecha de Ingreso: marzo-2010
Ubicación: Mérida, Venezula
Mensajes: 73
Antigüedad: 14 años
Puntos: 0
Respuesta: Buenas, ayuda con TextCtrl y wx.EVT_TEXT

Código python:
Ver original
  1. if Nombre=="" or re.match("[^a-zA-Z]", Nombre) :
  2.            
  3.             dialogo = wx.MessageDialog(self.ventana, u'El campo Nombre esta vacio o se               introdujo un caracter no valido', u'Informacion', wx.OK | wx.ICON_INFORMATION)
  4.             dialogo.ShowModal()
  5.             dialogo.Destroy()
  6.             self.cuadro_Nombre.SetFocus()]

Ok, en ese caso "Nombre" seria variable correcto? y al decirle [^a-zA-Z] Estoy negando a-zA-Z lo que no estoy seguro es si al introducirle entonce el comportamiento seria que si la coincidencia no es una letra devuelve el aviso. O no estoy seguro si podria ser de otra manera, al decirle al
Código:
 not (re.match [a-zA-Z])
Agradezco la respuesta y cualquier explicación con respecto al re.match

Última edición por AlvaroG; 07/04/2010 a las 10:59 Razón: resaltado de sintaxis
  #7 (permalink)  
Antiguo 07/04/2010, 11:35
AlvaroG
Invitado
 
Mensajes: n/a
Puntos:
Respuesta: Buenas, ayuda con TextCtrl y wx.EVT_TEXT

Lo que escribiste es correcto, así es como funcionará.
el "not" funcionará igual de bien, aunque los paréntesis no son necesarios

if not re.match(....)



Saludos.

Etiquetas: Ninguno
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 10:31.