Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 676
rectangletangle Avatar asked Dec 28 '25 21:12

rectangletangle


2 Answers

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.

like image 90
Bryan Oakley Avatar answered Dec 30 '25 09:12

Bryan Oakley


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()
like image 27
Bryan Avatar answered Dec 30 '25 10:12

Bryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!