tkinter text width

Jeremy Bowers jerf at jerf.org
Wed Apr 27 15:10:52 EDT 2005


On Wed, 27 Apr 2005 10:52:14 -0700, James Stroud wrote:
> This is more or less what I would like, but I would also like to probe the 
> Text to see how many characters it thinks it can display within the container 
> window. I am formatting text dynamically and so I rely on the width. I am not 
> after the built in "wrap" option, it does not do what I want. But, say if 
> wrap were turned on, it would be good to know how many characters the Text 
> would wrap at.

I have extensive experience with trying to get text containers to do this.
It is not easy. You have two choices:

1. Give up. You can't tell anyhow if you're using a proportional font.

2. Use a fixed-width font and manually wrap. (It's pretty easy then, you
can ask the font for how wide any char is and do the math from there.)

I have 70 line function that tries to replicate the Tk wrapping algorithm
in the proportional text case, and it *still* doesn't work. For one thing,
I actually found some bugs in the wrapping code (if a Unicode character
gets into just the right position, it can actually run off the right end
of the text widget, even if the widget is being wrapped), so completely
matching the layout seems infeasible.

I would strongly, strongly suggest finding another way to do what you are
trying to do. I have blown many, many hours on this problem, and I found
no simple logic. The edge cases kill you; while Tk is consistent (same
text, same wrap every time), sometimes it wraps a word if it goes up to
the edge, sometimes if it's one pixel off, damned if I can find a pattern
(probably has something to do with trying to space the letters out,
kerning or one of its simpler friends), and it probably changes
periodically anyhow... and note based on this I can't even guarantee #2
above, if you get unlucky.

Basically, I'm pretty sure you can't do this.




More information about the Python-list mailing list