0

I am a "novice" python user.

I have a listbox using tkinter and I want to format the list entries so they are aligned, and I have the following:

from Tkinter import *
master = Tk()

info=[  ['sue', 1, 'Argentina', 'Bsc'],
    ['peggy-sue', 17, 'U.K.', 'Bsc'],
    ['susie', 234, 'France', 'BA'] 
]

listbox = Listbox(master, width=60)
listbox.pack()

listbox.insert(END, "{:<15s}  {:>5s}  {:<25s}  {:<5s}".format("Name","id","Nationality","Qual") )

for i  in range(len(info)):
    item = "{:<15s}  {:>5d}  {:<25s}  {:<5s}".format(info[i][0],info[i][1],info[i][2],info[i][3])
    print item  # Gives nicely formatted lines
    listbox.insert(END, item)  #Lines are not nicely formatted in listbox

mainloop()

Can anyone explain why the listbox entries are not nicely formatted as the print line is?

I know about multi-column listboxes (e.g. Display Listbox with columns using Tkinter?) and so I don't need a solution, I am interested in why things aren't working as I had expected.

Thanks

1
  • You need to change the number of whitespaces between elements depending upon the length of each element. I'll see if I can make it work but that should be fairly simple to accomplish. Commented May 19, 2017 at 9:59

2 Answers 2

2

Your default font doesn't use equal widths for characters. Try, for example (assuming you are on Windows):

listbox = Listbox(master, width=60, font='consolas')

This results in the following:

TKinter window using Consolas, with equal spacing

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this answers my question. I am on linux, where font='mono' works
@TCJUK glad to hear it, and I'll keep 'mono' in mind for Linux in future! You can mark this as the answer to your question by clicking the tick to the left of the answer!
0

Not as good as @asongtoruin but

from Tkinter import *
master = Tk()

info=[  ['sue', 1, 'Argentina', 'Bsc'],
        ['peggy-sue', 17, 'U.K.', 'Bsc'],
        ['susie', 234, 'France', 'BA'] 
]

heads = ["Name","id","Nationality","Qual"]
listbox = Listbox(master, width=60)
listbox.pack()
fixedlen = 10
listbox.insert(END, ("{:<15s}"+(fixedlen-len(heads[0]))*" " +"{:>5s}"+(fixedlen-len(heads[1]))*" " +"{:<25s}"+(fixedlen-len(heads[2]))*" " +"{:<5s}").format(heads[0],heads[1],heads[2],heads[3]) )

for i  in range(len(info)):
    item = ("{:<15s}"+(fixedlen-len(str(info[i][0])))*" " +"{:>5d}"+(fixedlen-len(str(info[i][1])))*" " +"{:<25s}"+(fixedlen-len(str(info[i][2])))*" " +"{:<5s}").format(info[i][0],info[i][1],info[i][2],info[i][3])
    print item  # Gives nicely formatted lines
    listbox.insert(END, item)  #Lines are not nicely formatted in listbox

mainloop()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.