Text Widget size

Eric Brunel eric.brunel at pragmadev.com
Tue May 21 14:27:05 EDT 2002


Salim Zayat wrote:
> Hey all.  What's up?  I have a quick question about the Tkinter Text
> widget.  If I have a string of text inserted, is there a way to change
> the size of the Text widget to fit it perfectly, i.e. changing the height
> and width to display all the lines of Text that are there and not have
> any extra lines?

That shouldn't be too difficult: just create your text with the minimum 
width and height (1 and 1...) and bind a callback to the <KeyRelease> event 
getting the number of lines in the text and the length of the longest line 
and set them respectively as the height and width of the Text object:

t = Text(..., width=1, height=1)
def resize(event):
  lines = t.get(1.0, END).splitlines()
  maxW = 0
  if lines: maxW = max([len(l) for l in lines])
  t.configure(width=maxW, height=len(lines))
t.bind("<KeyRelease>", resize)

Be warned: this doesn't work in all cases... If you do an t.insert or a 
t.delete, you'll have to call the resize function manually. There are also 
far more complex issues with non-default fonts, especially proportional 
fonts, and tab management, that will make the simple method above miserably 
fail... But you get the idea.

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




More information about the Python-list mailing list