2

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()

2 Answers 2

4

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.

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

2 Comments

Hm that does work, but now different rows have different font sizes, unless I format all this way. Is there an option to adjust the fontsize and/or specify fontsizes for each column? I haven't seen anything like this in the tag options.
@throwaway17434, You don't need to call tree.tag_configure only multiple time. Call it once. (Even though tag='monospace' is required for every tree.insert)
1

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

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.