Python:根据* actual * length填充字符串

时间:2015-07-10 13:56:52

标签: python string tkinter string-formatting

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

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

2 个答案:

答案 0 :(得分:2)

在Windows上,此代码完全排列“结束”:

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()的值,并根据操作系统使用其他固定宽度字体。

答案 1 :(得分:2)

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

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

我通常建议

show='headings'
当您需要列表(而不是树)时,Treeview构造函数中的

选项。