Josh Clayton
Josh Clayton

Reputation: 97

Listbox Python Columns

I am trying to develop a script that allows me to keep my formatting within my listbox.

from Tkinter import *
from tabulate import tabulate
master = Tk()

listbox = Listbox(master)
listbox.pack()

table = [["spam",42],["eggs",451],["bacon",0]]
headers = ["item", "qty"]
tb = tabulate(table, headers, tablefmt="plain")

listbox.insert(END,tb)

mainloop()

End Result the listbox populated with the tb formatting:

enter image description here

QUESTION: HOW DO I GET MY LISTBOX TO APPEAR LIKE THE PICTURE ABOVE THAT I USED TABULATE TO FORMAT?

I've noticed treeview seems to have some limitations with the horizontal box and expanding the columns without adjusting the entire GUI so I'd decided this might be a more shake-shift way that will suit my needs just fine.

Upvotes: 1

Views: 5101

Answers (1)

One option may be to use str.format() to align each insert into the listbox:

from Tkinter import *
import tkFont

master = Tk()
master.resizable(width=False, height=False)
master.geometry('{width}x{height}'.format(width=300, height=100))
my_font = tkFont.Font(family="Monaco", size=12) # use a fixed width font so columns align

listbox = Listbox(master, width=400, height=400, font=my_font)
listbox.pack()

table = [["spam", 42, "test", ""],["eggs", 451, "", "we"],["bacon", "True", "", ""]]
headers = ["item", "qty", "sd", "again"]

row_format ="{:<8}{sp}{:>8}{sp}{:<8}{sp}{:8}" # left or right align, with an arbitrary '8' column width 

listbox.insert(0, row_format.format(*headers, sp=" "*2))
for items in table:
    listbox.insert(END, row_format.format(*items, sp=" "*2))
mainloop()

Which appears to match the output you got using tabulate:

enter image description here
Another option could be use a Grid layout.

Upvotes: 2

Related Questions