Search code examples
pythonevent-handlingwxpythonwxwidgets

wxpython event handling: GetValue after key is pressed


I want to get the value of a TextCtrl every time this TextCtrl gets changed. My code returns me the "old" value (like before I pressed the key) - but I want to get the "new" value with the key I pressed. For example, when the Value of my TC is "123" and I add a "4", I still get "123" returned, but I want to get "1234".

class pageThree(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent,size=(800,600))
        self.pageThree=wx.Panel(self,size=(800,600))    
        self.TC = wx.TextCtrl(self.pageThree,-1,pos=(100,150),size=(60,20))
        self.TC.Bind(wx.EVT_KEY_DOWN, self.getValue)

    def getValue(self, event):
        print self.TC.GetValue()

As I only work with integers in this TC, I tried to add + event.GetKeyCode() - 48, but this does not work when I delete a value instead of adding one =/


Solution

  • You need to bind to wx.EVT_TEXT instead of wx.EVT_KEY_DOWN. See the following example:

    import wx
    
    ########################################################################
    class MyPanel(wx.Panel):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self, parent):
            """Constructor"""
            wx.Panel.__init__(self, parent)
    
            self.text = wx.TextCtrl(self)
            self.text.Bind(wx.EVT_TEXT, self.onText)
    
        #----------------------------------------------------------------------
        def onText(self, event):
            """
            """
            print self.text.GetValue()
    
    
    ########################################################################
    class MainFrame(wx.Frame):
        """"""
    
        #----------------------------------------------------------------------
        def __init__(self):
            """Constructor"""
            wx.Frame.__init__(self, None, title="Events!")
            panel = MyPanel(self)
            self.Show()
    
    #----------------------------------------------------------------------
    if __name__ == "__main__":
        app = wx.App(False)
        frame = MainFrame()
        app.MainLoop()