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?
What you want to do isn't directly supported by the widget. You can almost get there by using a couple of tricks. For example, you can set the wrap attribute to wrap at word or character boundaries, then make sure the widget is never wider than 80 characters (this requires using pack/grid/place options appropriately).
This technique will work fine for fixed-width fonts, but for variable width fonts it won't always wrap at 80 characters. That is because when you set the width to 80 characters it's actually setting it to a specific pixel width based on 80 times the width of an average character (specifically, the 0 (zero) character, last time I checked).
Of course, you can always force it to wrap at 80 characters by monitoring text insertions and deletions and handling the wrapping yourself, but that's usually more work than is worth the effort.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With