Tkinter label height to fit content

rantingrick rantingrick at gmail.com
Tue Sep 6 23:37:57 CEST 2011


Or if you prefer the alternating background approach...


##################
# Easy_as.py
##################
import Tkinter as tk
from ScrolledText import ScrolledText
import tkFont
import random
END = 'end'
INSERT = 'insert'
#
# Create some puesdo data.
data = [
    '{0}.{1}'.format(x, 'blah'*random.randint(4, 50))
    for x in range(100)
    ]
##print data
#
# Create the main window and a scrolled text widget.
root = tk.Tk()
font = tkFont.Font(family='times', size=13)
textbox = ScrolledText(
    root,
    width=60,
    height=20,
    font=('Times', 10),
    wrap=tk.WORD,
    )
textbox.pack(
    fill=tk.BOTH,
    expand=True,
    padx=5,
    pady=5,
    )
#
# Add a tag to the very end of the widget and
# configure the tag only once!
textbox.tag_add('one', END)
textbox.tag_config('one', background='gray')
#
# Iterate over the lines stuffing them into the textbox.
idata = iter(data)
sidx = 1.0
while True:
    try:
        textbox.insert(END, idata.next()+"\n")
        textbox.tag_add('one', sidx, INSERT)
        textbox.insert(END, idata.next()+"\n")
        print sidx, textbox.index(END)
        sidx = textbox.index(INSERT)
    except StopIteration:
        break
#
# Start the event loop.
root.mainloop()
##################
# End
##################




More information about the Python-list mailing list