Tkinter measurements

Eric Brunel eric_brunel at despammed.com
Tue Sep 28 04:26:01 EDT 2004


John Velman wrote:
> I want to draw a box around a short piece of text in canvas (one line
> text).  I know how to do it if I place the text on the canvas first,then
> draw the box around it. 
> 
> Is there a way to find out the dimensions of the text bounding box before
> drawing it?

First: why do you want to do that? The most used method is to draw the text 
before, get its bounding box, then draw the box. Why do you want to do the opposite?

Anyway, there are some ways to get the size of the displayed text via the tkFont 
module. Example:

--------------------------------------------------------------
from Tkinter import *
from tkFont import Font

root = Tk()
cnv = Canvas(root)
cnv.pack()

## This text item is only used to get the default font in the canvas
t = cnv.create_text(0, 0, text='')
f = Font(font=cnv.itemcget(t, 'font'))

s = 'spam, spam and spam'
cnv.create_text(10, 10, text=s, anchor=W)
cnv.create_line(10, 15, 10 + f.measure(s), 15)

root.mainloop()
--------------------------------------------------------------

So you can get the text width quite easily. For the text height, it only depends 
on the font size and the number of lines in the text, so computing it "manually" 
seems reasonable.

> Also, is there a method for converting from pixels to inches or inches to
> pixels (for canvas)?

The solution I use is just to multiply or divide by 72. Be careful with that: if 
you use it on font sizes, some windowing systems try to be smart and consider 
the screen resolution when displaying text. To avoid this, you can use negative 
font sizes (e.g. myText.configure(font=('helvetica', -12))). A negative font 
size is always considered in "regular" pixels (one inch / 72), and does not 
depend on the screen resolution.

HTH
-- 
- Eric Brunel <eric (underscore) brunel (at) despammed (dot) com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com




More information about the Python-list mailing list