gwthm.in
gwthm.in

Reputation: 638

Is there any way to fix the column width in listbox in Tkinter?

I want to show some items in listbox. Some are very short and some are very large(10-15 characters). Like below one,

1. facebook  gowtham95****@gmail.com

2. gmail  [email protected]

3. stackoverflow   stackusername

I want to show them neatly like...

1. facebook    gowtham95****@gmail.com

2. gmail       [email protected]

3. stack..     stackusername

Is there anyway to fix the column width in listbox in Tkinter?

and onemore thing, I want to label it above as id, domain and username. I don't want to use labels. I want to mention it in listbox itself, is there anyway?

Upvotes: 2

Views: 1332

Answers (1)

furas
furas

Reputation: 142641

You could use string formating - but it requires some monospaced font, and you have to find the longest string in column(s).

import Tkinter as tk

master = tk.Tk()
master.geometry('600x100')

lb = tk.Listbox(master, font='monospace') # some monospaced font
lb.pack(fill=tk.BOTH, expand=1)

#---

data = [
    ('1', 'facebook', 'gowtham95****@gmail.com'),
    ('2', 'gmail', '[email protected]'),
    ('3', 'stackoverflow', 'stackusername')
]

longest_1 = max( len(x[1]) for x in data )
longest_2 = max( len(x[2]) for x in data )

for x in data:
    line = '%s | %*s | %*s |' % (x[0], -longest_1, x[1], -longest_2, x[2])    
    lb.insert(tk.END, line)

#---

tk.mainloop()

enter image description here

Upvotes: 1

Related Questions