How do I get the current length of the Text in a Tkinter Text widget
Question: I am writing a light webtexting application, and I'm trying to display the
current number of characters in a TKinter Text widget used for writing the
message to be sent in the webtext. The code I have at the moment can be seen
below, I'm using python

    
    
    root = Tk()
    
    msgLabel = Label(text="Message")
    msgLabel.grid(row=0, column=0)
    msg = Text(width=40, height=4, wrap="word")
    msg.grid(row=0, column=1, padx=10, pady=5)
    
    #Try to display number of characters within message to user
    charCount = Label(text="Character Count: "+str(len(meg.get("1.0", 'end-1c')))
    charCount.grid(row=1, column=1, pady=5, padx=5)
    
    root.mainloop()
    

I'd like to be able to display the number of characters in the message written
by the user, since there is a 160 character limit to each webtext. Is it
possible to display the current character length, that updates as text is
inserted and removed? Thanks in advance


Answer: We use `StringVar` to set new text to label. We need to bind `msg` for key
pressing.

    
    
    from Tkinter import *
    root = Tk()
    #-----------------------------------------------
    def update(event):
        var.set(str(len(msg.get("1.0", 'end-1c'))))
    #-----------------------------------------------
    
    msgLabel = Label(text="Message")
    msgLabel.grid(row=0, column=0)
    msg = Text(width=40, height=4, wrap="word")
    msg.grid(row=0, column=1, padx=10, pady=5)
    
    #----------------
    var = StringVar()
    #----------------
    
    #Try to display number of characters within message to user
    #----------------------------------
    charCount = Label(textvariable=var)
    #----------------------------------
    charCount.grid(row=1, column=1, pady=5, padx=5)
    
    #------------------------
    msg.bind("<Key>", update)
    #------------------------
    
    root.mainloop()
    

