Version 2 of Setting the size of a textbox in pixels

Updated 2011-04-15 04:34:26 by MG

I have an application with text boxes on a canvas, and I want to be able to resize them using the mouse; that means setting the height and width of the textbox in points rather than characters. Not having found anything on this subject here, I present my own humble effort:

  proc SizeText {w dx dy} {
    set font [$w cget -font]
    set width [expr ($dx-10)/[font measure $font "n"]]
    set height [expr ($dy-10)/[font metric $font -linespace]]
    $w config -width $width -height $height
  }

where w is the textbox, and dx and dy are the width and height of the box in points, respectively.

Notes:

  • This assumes that the text box only includes one font.
  • I use the width of the letter "n" as my conversion factor between characters and points. This seems to work but I have no idea what the real conversion factor should be.
  • The 10's should probably be replaced by twice the highlightthickness or something like that.

MG Tk uses the number "0" for measuring the size of a font's characters, IIRC.