Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Resize text to contents

Tags:

python

tkinter

Is it possible to have a Tkinter text widget resize to fit its contents?

ie: if I put 1 line of text it will shrink, but if I put 5 lines it will grow

like image 704
SquidsEnMasse Avatar asked Jul 18 '12 14:07

SquidsEnMasse


1 Answers

The only way I can think of accomplishing this is to calculate the width and height every time the user enters text into the Text widget and then set the size of the widget to that. But the limitation here is that only mono-spaced fonts will work correctly, but here it is anyway:

import Tkinter

class TkExample(Tkinter.Frame):
   def __init__(self, parent):
      Tkinter.Frame.__init__(self, parent)
      self.init_ui()

   def init_ui(self):
      self.pack()
      text_box = Tkinter.Text(self)
      text_box.pack()
      text_box.bind("<Key>", self.update_size)

   def update_size(self, event):
      widget_width = 0
      widget_height = float(event.widget.index(Tkinter.END))
      for line in event.widget.get("1.0", Tkinter.END).split("\n"):
         if len(line) > widget_width:
            widget_width = len(line)+1
      event.widget.config(width=widget_width, height=widget_height)

if __name__ == '__main__':
    root = Tkinter.Tk()
    TkExample(root)
    root.mainloop()
like image 84
smont Avatar answered Nov 08 '22 21:11

smont