1

OK, So the base problem is this: I have a set of strings I want display, followed by relevant data that is aligned vertically, the set of strings will be of variable length. using the method described here: Python spacing and aligning strings produces results less than desirable. View the fruits of my efforts here. I speculate that the width of the characters is not fixed from character to character inside a listbox like it is with a print command, which would explain why my list box columns are not aligned.

this is the code I am currently using, Its crude compared to the solutions shown on the other question, but it does function correctly in that it pads the data with enough spaces to make each the same length.

stringlist=['thistext','thattext','somemoretext','txt','text with spaces']

tagnmlen=0
for tags in stringlist:
    if len(tags) > tagnmlen:
        tagnmlen=len(tags)

for text in stringlist:
    strg = text.ljust(tagnmlen) + ',' + "another bit of data"
    listbox.insert(END,strg)

I'd rather not change the font of the Listbox to something that would have consistent spacing, and I'd rather not set multiple Listboxes next to one another.

Community
  • 1
  • 1
Josh Duzan
  • 80
  • 1
  • 8

1 Answers1

1

If what you want to do is to align two columns of strings in a single listbox, I would suggest the following:

  1. Use tkFont to measure the lengths of the left strings (for the exact font used) as described here

  2. Add spaces between left and right strings so that the right string always start at the same position (in practice this position will vary by a few pixels because even the "space" character is a few pixels wide)

In the end you'll get something like this:

screenshot

Code (Python 2.x)

import Tkinter as Tk
import tkFont

#Create a listbox
master = Tk.Tk()
listbox = Tk.Listbox(master, width=40, height=20)
listbox.pack()

# Dummy strings to align
stringsLeft = ["short", "medium", "extra-------long", "short", "medium", "short"]
stringsRight = ["one", "two", "three", "four", "five", "six"]

# Get the listbox font
listFont = tkFont.Font(font=listbox.cget("font"))

# Define spacing between left and right strings in terms of single "space" length
spaceLength = listFont.measure(" ")
spacing = 12 * spaceLength

# find longest string in the left strings
leftLengths = [listFont.measure(s) for s in stringsLeft]
longestLength = max(leftLengths)

# combine left and righ strings with the right number of spaces in between
for i in range(len(stringsLeft)):
    neededSpacing = longestLength + spacing - leftLengths[i]
    spacesToAdd = int(round(neededSpacing/spaceLength))
    listbox.insert(Tk.END, stringsLeft[i] + spacesToAdd * " " + stringsRight[i])

Tk.mainloop()

For Python 3.x, replace the import statements with:

import tkinter as Tk
from tkinter import font as tkFont
Josselin
  • 2,593
  • 2
  • 22
  • 35