【问题标题】:Python Padding strings to align columns in a Tkinter ListBox widgetPython 填充字符串以对齐 Tkinter ListBox 小部件中的列
【发布时间】:2017-08-17 22:55:22
【问题描述】:

好的,所以基本问题是这样的: 我有一组要显示的字符串,然后是垂直对齐的相关数据,这组字符串的长度是可变的。使用此处描述的方法:Python spacing and aligning strings 产生的结果不太理想。查看我的努力成果here。我推测字符的宽度在列表框中的字符之间不是固定的,就像使用打印命令一样,这可以解释为什么我的列表框列没有对齐。

这是我目前正在使用的代码,与其他问题中显示的解决方案相比,它很粗糙,但它确实可以正常工作,因为它用足够的空间填充数据以使每个数据的长度相同。

stringlist=['thistext','thattext','somemoretext','txt','text with spaces']

tagnmlen=0
for tags in stringlist:
    if len(tags) > tagnmlen:
        tagnmlen=len(tags)

for text in stringlist:
    strg = text.ljust(tagnmlen) + ',' + "another bit of data"
    listbox.insert(END,strg)

我宁愿不将 Listbox 的字体更改为具有一致间距的字体,也不希望多个 Listbox 彼此相邻设置。

【问题讨论】:

    标签: python tkinter listbox string-formatting


    【解决方案1】:

    如果你想做的是在一个列表框中对齐两列字符串,我建议如下:

    1. 使用 tkFont 测量左侧字符串的长度(对于所使用的确切字体),如 here

    2. 所述
    3. 在左右字符串之间添加空格,这样右字符串总是从相同的位置开始(实际上这个位置会相差几个像素,因为即使是“空格”字符也是几个像素宽)

    最后你会得到这样的东西:

    代码(Python 2.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 语句替换为:

    import tkinter as Tk
    from tkinter import font as tkFont
    

    【讨论】:

    • 工作就像一个魅力,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-01-23
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2018-11-23
    • 2015-06-06
    相关资源
    最近更新 更多