Reputation: 52911
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?
Upvotes: 3
Views: 10551
Reputation: 415
The question is a little unclear for me.
If you want to set the width of the text box. Then you can set the width when you instance the Text class. Width is in characters by default. The actual pixel width is determined by the text widgets default font. Note that characters exceeding confines of the box will cause the text to 'page' right after each character width is met.
chars = 5 # 5 characters wide
Text(parent, width = chars, font = ('Helvetica, 24'))
# change the font family and size to get different sized text boxes
You can also redefine the Text Widgets width after it is created:
textWidget.configure(width = 5)
If you want to limit the input into the text widget. I wrote a solution on another thread for that.
Read my reply here
As stated in the comments there are other widgets that can also handle the task. The entry widget being one of them.
If this has been useful then please up vote. If you have comments on how I can communicate more clearly I'd appreciate that.
Upvotes: 0
Reputation: 385900
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.
Upvotes: 3
Reputation: 6699
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()
Upvotes: 1