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
Edit: short method:
text.pack(side="top", fill="both", expand=True, padx=0, pady=0)
By re-using sc0tt's answer, and Bryan Oakley's answer here Get of number of lines of a Text tkinter widget, we can have this ready-to-use code (posted here for future reference) that also works for proprtional fonts :
import Tkinter as Tk
import tkFont
class Texte(Tk.Text):
def __init__(self, event=None, x=None, y=None, size=None, txt=None, *args, **kwargs):
Tk.Text.__init__(self, master=root, *args, **kwargs)
self.font = tkFont.Font(family="Helvetica Neue LT Com 55 Roman",size=35)
self.place(x=10,y=10)
self.insert(Tk.INSERT,' blah ')
self.config(font=self.font)
self.update_size(event=None)
bindtags = list(self.bindtags())
bindtags.insert(2, "custom")
self.bindtags(tuple(bindtags))
self.bind_class("custom", "", self.update_size)
def update_size(self, event):
width=0
lines=0
for line in self.get("1.0", "end-1c").split("\n"):
width=max(width,self.font.measure(line))
lines += 1
self.config(height=lines)
self.place(width=width+10)
root = Tk.Tk()
root.geometry("500x500")
Texte()
root.mainloop()