Tkinter Listbox string formatting question - how to kill a dancingsnake ?

Hendrik van Rooyen mail at microcorp.co.za
Thu Nov 2 10:16:59 CET 2006


"Fredrik Lundh" <fredrik at pythonware.com> wrote:


<lots of stuff to for me to download and read up>


In the meantime, I have produced this evil hack, that takes advantage of the
difference in pixel widths between the space, and either the fullstop or the
single quote...

It will only work if you have quite a lot of space to waste between columns, and
I have only tested it for two sizes of Lucida and Helvetica - and for a fixed
font like courier it seems to do no harm other than the cpu time it wastes...

If the difference in width is one pixel, it lines up the next thing to be added
to the string exactly, else it almost gets it right...

I find the few (up to one less than there are pixels in a space) characters it
adds into the line less visually disturbing than the dancing snake column caused
by the full space width variation.

anyway for what its worth, here it is:

# this does some text padding to try to line variable font stuff up

def pad_text(txt,pixlen,fontp):
    """This does padding up to a pixel value exploiting differences
    between space, fullstop or single quote widths.
    txt is a text string
    pixlen is an int - the number of pixels to "tab" to
    fontp is the font parameter
    """

    a = fontp.measure(txt)
    diff = pixlen - a
    if diff < 0:
        return "string too long too fit in pixels"
    spsize = fontp.measure(' ')
    fssize = fontp.measure('.')
    sqsize = fontp.measure("'")
    repchr = ' '
    rpsize = spsize
    numr = 0
    rpdiff = 0
    if spsize != fssize:
        repchr = '.'
        rpsize = fssize
        rpdiff = abs(fssize - spsize)
    elif spsize != sqsize:
        repchr = "'"
        rpsize = sqsize
        rpdiff = abs(spsize - sqsize)
    numspace, rem = divmod(diff,spsize)
    if rem == 0:
        numr = 0
    else:
        if spsize < rpsize:
            numspace -= rem/rpdiff
            numr = rem/rpdiff
        elif spsize > rpsize:
            numr = (spsize - rem)/rpdiff
            numspace = numspace - numr + 1
    numspace -= 2
    txt = txt + '  '
    while numr > 0:
        txt = txt + repchr
        numr -= 1
    while numspace > 0:
        txt = txt + ' '
        numspace -= 1
    return txt

Feel free to play the critic...

- Hendrik





More information about the Python-list mailing list