简体   繁体   English

在tkinter.ttk.Treeview列中格式化文本

[英]Format Text in tkinter.ttk.Treeview column

I would like to know how to justify the text in a ttk.Treeview column. 我想知道如何在ttk.Treeview专栏中证明文本的合理性。 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. 编辑:它是用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 : 使用tkinter.ttk.Treeview.tag_configure使用monospace字体:

...
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. 有关headingcolumn方法的锚点和其他选项的更多详细信息,请参阅Tkinter 8.5参考:来自New Mexico Tech的Python GUI

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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