简体   繁体   中英

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

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 .

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 Tkinter 8.5 reference: a GUI for Python from New Mexico Tech.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM