throwaway17434
throwaway17434

Reputation: 831

Format Text in tkinter.ttk.Treeview column

I would like to know how to justify the text in a ttk.Treeview column. Below is an example of what I mean. Notice the dates and how the digits are not properly under each other. I think it has something to do with the spacing, but I could be wrong.

EDIT: It's written in Python 3.

#! coding=utf-8
import pickle
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter import ttk

# Create Example
root = tk.Tk()
root.minsize(200,300)
tree = ttk.Treeview(root,columns=("date"))
tree.heading("#0"  , text='Sample', anchor=tk.W)
tree.column("#0", stretch=0)
tree.heading("date", text='Date', anchor=tk.E)
tree.column("date", stretch=0)

ABC   = ["A","B","C","D","E"]
dates = ["3.4.2013", "14.10.400", "24.12.1234", "1.10.1", "14.7.123"]
tree.insert("",iid="1", index="end",text="No Format")
for i in range(len(ABC)):
dates2 = dates[i].split(".")
    date   = "{:<2}.{:<2}.{:<4}".format(dates2[0],dates2[1],dates2[2])
    tree.insert("1",iid="1"+str(i), index="end",text=ABC[i], value=[dates[i]])
tree.see("14")
tree.insert("",iid="2", index="end",text="With Format")
for i in range(len(ABC)):
    dates2 = dates[i].split(".")
    date   = "{:>2}.{:>2}.{:>4}".format(dates2[0],dates2[1],dates2[2])
    tree.insert("2",iid="2"+str(i), index="end",text=ABC[i], value=[date])
tree.see("24")

tree.pack(expand=True,fill=tk.BOTH)

root.mainloop()

Upvotes: 2

Views: 10950

Answers (2)

lemi57ssss
lemi57ssss

Reputation: 1380

You can justify the text in the date column in the same way as you have justified the text in the date heading by using the anchor option.

tree.heading("date", text='Date', anchor=tk.E)
tree.column("date", stretch=0, anchor=tk.E)

More detailed information on anchor and other options for the heading and column methods can be found in TkDocs Treeview

Upvotes: 1

falsetru
falsetru

Reputation: 368944

Use monospace font using tkinter.ttk.Treeview.tag_configure:

...
for i in range(len(ABC)):
    dates2 = dates[i].split(".")
    date   = "{:>2}.{:>2}.{:>4}".format(dates2[0],dates2[1],dates2[2])
    tree.insert("2",iid="2"+str(i), index="end",text=ABC[i], value=[date],
                tag='monospace') # <----
tree.tag_configure('monospace', font='courier') # <----
...

See Tag Options.

Upvotes: 4

Related Questions