Python: fill string according to * actual * length

In python, it's easy to insert a string with spaces according to the number of characters. For instance:

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

Conclusion:

aaa       end
www       end

Which looks great here or on any other display where the size of all characters is equal. But when I output these two lines in the program Tkinter, they are not aligned, because the characters "a" and "w" have different lengths in any Tkinter font.

How can I align the lines in Tkinter?

My code is:

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

I want the object and date to be aligned between all lines.

+4
source share
2 answers

On Windows, this code exactly matches the "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() .

+2

, . . tkinter , .

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

show='headings'

Treeview, ( ).

+2

All Articles