如果您想在一个列表框中对齐两列字符串,我建议如下:在左字符串和右字符串之间添加空格,以便右字符串始终从同一位置开始(实际上,此位置将变化几个像素,因为即使是“空格”字符也是几个像素宽)
最后你会得到这样的结果:
代码(Python2.x)import Tkinter as Tk
import tkFont
#Create a listbox
master = Tk.Tk()
listbox = Tk.Listbox(master, width=40, height=20)
listbox.pack()
# Dummy strings to align
stringsLeft = ["short", "medium", "extra -long", "short", "medium", "short"]
stringsRight = ["one", "two", "three", "four", "five", "six"]
# Get the listbox font
listFont = tkFont.Font(font=listbox.cget("font"))
# Define spacing between left and right strings in terms of single "space" length
spaceLength = listFont.measure(" ")
spacing = 12 * spaceLength
# find longest string in the left strings
leftLengths = [listFont.measure(s) for s in stringsLeft]
longestLength = max(leftLengths)
# combine left and righ strings with the right number of spaces in between
for i in range(len(stringsLeft)):
neededSpacing = longestLength + spacing - leftLengths[i]
spacesToAdd = int(round(neededSpacing/spaceLength))
listbox.insert(Tk.END, stringsLeft[i] + spacesToAdd * " " + stringsRight[i])
Tk.mainloop()
对于Python 3.x,将import语句替换为:
^{pr2}$