Text Widget size

J.Jacob joost_jacob at hotmail.com
Wed May 22 07:35:12 EDT 2002


> [Salim Zayat]
> 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?

Here is the method (called resize()) in class TextMap that does
what you asked for when called without parameters.  class TextMap
is of type Tkinter.Frame and has a .text attribute of type
Tkinter.Text.  Works with python 1.5.2 or later.

I think you can figure out how it is implemented now, for more
details: the class TextMap is in the textui module I submitted to
parnassus, you can also get it at
http://www.cwi.nl/~jacob/textui.py



    def resize(self, height=None, width=None):
        if not (height or width):       # fit window to displayed
                                        # text inside
            textstr = self.gettext()
            self.width = 0
            self.height = 0
            for s in string.split(textstr, '\n'):
                self.height = self.height + 1
                if len(s) > self.width: self.width = len(s)
            self.resize(height=self.height, width=self.width)
        else:
            if height:
                self.height = height
                self.text.config(height=height)
            if width:
                self.width = width
                self.text.config(width=width)
            self.text.update()

    def gettext(self):
        "Return the data (string) in the window"
        return self.text.get('1.0', END+'-1c')          # first
            # through last END points to just beyond the last
            # character in the text string '-1c' because this
            # widget adds a trailing newline char to its
            # contents



More information about the Python-list mailing list