[Tutor] key_press_event

John CORRY john.corry at ntlworld.com
Sun Aug 13 11:56:32 CEST 2006


Hi,

I'm using Python 2.4, pygtk and Glade2.

I have a few text entries.  I am trying to put validation on the text
entry boxes.  I am trying to catch the key_press_event, check the key
that has been pressed and either allow it or put back the old text.  The
code is below with the output after it.

class Test:
    def __init__(self):
        self.wTree = gtk.glade.XML ("test.glade", "window1")
        dic={"on_window1_delete_event" : self.quit10, }
        self.wTree.signal_autoconnect(dic)
        
        cancel = self.wTree.get_widget("button2")
        cancel.connect("clicked", self.quit, )
        text1 = self.wTree.get_widget("entry1")
        text2 = self.wTree.get_widget("entry2")
        text2.connect("key_press_event",self.callback3)
        login = self.wTree.get_widget("button1")
        login.connect("clicked", self.callback2, text1,text2)
    def callback3(self,data,widget):
        
        input = data.get_text()
        print input
        data.set_text("test")
       
        
    def callback2(self,data,text1,text2):
        print 'hello'
    def quit10(self,obj,data):
        gtk.main_quit()
        sys.exit(1)
    def quit(self,obj):
        gtk.main_quit()
        sys.exit(1)
if __name__ == '__main__':
    Test()
    try:
        gtk.threads_init()
    except:
            print "No threading was enabled when you compiled pyGTK!"
            import sys
            sys.exit(1)
    gtk.threads_enter()
    gtk.main()
    gtk.threads_leave()


The box starts of with 123 in it.  If I hit the 'a' key on the key board
I get the following result.

123 is printed and 'atest' appears in the text entry box.

Is there a way to catch the key_press (in this case the 'a') and check
to see if it is a number.  If it is not a number, ignore it.  If it is a
number accept it.  

Why does the 'a' appear in 'atest'.  It is like the code works first,
sets the text to 'test' and then the key press works and inserts the
'a'.  Do I need to disconnect the key press signal?

Thanks,

John. 




More information about the Tutor mailing list