Search code examples
pythontextfontswidthtkinter

How to set maximum width in characters for the Text widget?


I noticed the width argument for the Tkinter Text widget is in characters.

Is it possible to set a maximum width in characters for the text widget?


Solution

  • You can do this by binding to the Key, KeyPress, or KeyRelease events. But every implementation of this that I've seen is flaky. If you can get by with using an Entry widget instead of a Text widget, take a look at a Validating Entry Widget.

    Seems pretty simple to use (I do not include the ValidatingEntry and MaxLengthEntry classes for brevity):

    from Tkinter import *
    
    root = Tk()
    entry = MaxLengthEntry(root, maxlength=10)
    entry.pack(side=LEFT)
    root.mainloop()