Python:根据*实际*长度填充字符串

Python: padding string according to *actual* length

在python中很容易根据字符数用空格填充字符串。例如:

print "aaa".ljust(10) + "end"
print "www".ljust(10) + "end"

输出为:

aaa       end
www       end

这在此处或所有字符大小相等的任何其他显示中看起来都很棒。但是当我在 Tkinter 程序中输出这两个字符串时,它们没有对齐,因为字符 'a' 和 'w' 在任何 Tkinter 字体中都有不同的长度。

如何对齐 Tkinter 中的字符串?

我的代码:

from Tkinter import *

STANDARD_FONT = ("David",14)

TO = "TO"
SUBJECT = "SUBJECT"
DATE = "DATE"

content = [
    {TO:'Frye', SUBJECT:'Water Pipe Replacement Cost', DATE:'July 9'},
    {TO:'George', SUBJECT:'Fw: Cell phone reimbursement', DATE:'July 9'},
    {TO:'George, Tim', SUBJECT:'Travel', DATE:'July 10'},
    {TO:'Sandy, Jim', SUBJECT:'Fw: Welcome to WOW! - News', DATE:'July 10'},
    {TO:'Sandy, Jim', SUBJECT:'Re: Present from paulette', DATE:'July 10'},
    {TO:'George, Tim, Sandy, Jim', SUBJECT:'Voices Across Alaska: State Budget Priorities', DATE:'July 10'},
    {TO:'Frye', SUBJECT:'FW: Confirmation of the Novemberl 5th discussion', DATE:'July 10'},
    {TO:'Jim', SUBJECT:'Re: Happy Thanksgiving!', DATE:'July 11'}
]

def makeWindow () :
    global nameVar, phoneVar, select
    win = Tk()

    frame1 = Frame(win)
    frame1.pack()

    frame2 = Frame(win)       # Row of buttons
    frame2.pack()

    frame3 = Frame(win)       # select of names
    frame3.pack()
    scroll = Scrollbar(frame3, orient=VERTICAL)
    select = Listbox(frame3, yscrollcommand=scroll.set, height=17, width=100, font=STANDARD_FONT)
    scroll.config (command=select.yview)
    scroll.pack(side=RIGHT, fill=Y)
    select.pack(side=LEFT,  fill=BOTH, expand=1)
    return win

def format_mail_str(mail):
    to = "To: " + mail[TO]
    subject = mail[SUBJECT]
    date = mail[DATE]
    spacing = " " * 5

    return to.ljust(40) + spacing + subject.ljust(30) + spacing + date.ljust(15)


def setSelect () :
    select.delete(0,END)
    for mail in content:
        select.insert (END, format_mail_str(mail))

win = makeWindow()
setSelect ()
win.mainloop()

我希望主题和日期在所有行之间对齐。

在 Windows 上,此代码完全符合 "end":

import tkinter

root = tkinter.Tk()
displaytext1 = "aaa".ljust(10) + "end"
displaytext2 = "www".ljust(10) + "end"
tkinter.Label(root, text=displaytext1, font = "Courier").pack()
tkinter.Label(root, text=displaytext2, font = "Courier").pack()

root.mainloop()

检查 platform.system() 的值并根据操作系统使用其他固定宽度的字体。

我不会回答你提出的问题,但我会提出解决你问题的方法。 你想要的是几列。 在 tkinter 中有一个小部件,它是一个树视图。

例如: http://www.tkdocs.com/tutorial/tree.html

我通常推荐

show='headings'

当您需要列表(而不是树)时,Treeview 构造函数中的选项。