300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python字符填充对齐 Python填充字符串以对齐Tkinter列表框widg中的列

python字符填充对齐 Python填充字符串以对齐Tkinter列表框widg中的列

时间:2022-10-10 23:00:29

相关推荐

python字符填充对齐 Python填充字符串以对齐Tkinter列表框widg中的列

如果您想在一个列表框中对齐两列字符串,我建议如下:在左字符串和右字符串之间添加空格,以便右字符串始终从同一位置开始(实际上,此位置将变化几个像素,因为即使是“空格”字符也是几个像素宽)

最后你会得到这样的结果:

代码(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}$

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。