tkinter text width

Jeremy Bowers jerf at jerf.org
Wed Apr 27 17:42:57 EDT 2005


On Wed, 27 Apr 2005 12:52:21 -0700, James Stroud wrote:

> Thank you to everybody helping me. I think I am almost there...
> 
> On Wednesday 27 April 2005 12:10 pm, so sayeth Jeremy Bowers:
>> 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.)
> 
> How might I query the size of a fixed-width font in pixles? It appears that 
> the width of the font in points does not correlate with its width in pixels 
> based on some simple expriments I have done. Using cget("font") on the Text 
> gives back a string with the point size.

Ah, in that case you want the measure attribute of the font object.

http://www.pythonware.com/library/tkinter/introduction/x4671-methods.htm

> 
>> [snip some things to worry about]
>> Basically, I'm pretty sure you can't do this.
> 
> My setup is not very complicated, so I don't think I have to worry about 
> kerning, unicode, etc.. I am using a fixed width font (courier) only, and 
> only one size and am also quite comfortable with giving away several pixels 
> at the end of a line for "rounding errors" and will filter for a limited 
> alphabet consisting only of the numbers, the captial letters, and the space.
> 
> I think I can do this given these limitations.

Sounds like it.

What I did was set up unit test that threw random snippets at the text
widget, and compared how many lines my code thought the widget should
have, vs. what the widget claimed to have. This is how I discovered that
some unicode was wrapped incorrectly. You can get what the widget claims
to have by asking it for the geometric position of the last character with
the bbox method of the Text widget.

This is, however, probably not the answer you are looking for, because you
only get a bounding box if the text is currently visible on the screen.
This makes it fairly difficult to use to ask the widget *how far* off the
screen the text is. If it were that easy I would have said so earlier
:-) But you may find that useful too, as you cobble together a solution.




More information about the Python-list mailing list