TkInter列表框和.form的用法

2024-10-01 15:43:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用这个命令:

self.licenseBox.insert(END, "{:30}{:90}{:20}{:5}".format(item[0],
                                                    item[1], item[2], item[3]))

但是.format将添加项,然后添加列宽。例如if item[0] = "foo",第一列的宽度是33,这意味着下面的参数被关闭了三倍。在

有什么办法吗?在


Tags: 命令selfformat参数if宽度fooitem
1条回答
网友
1楼 · 发布于 2024-10-01 15:43:34

But .format will add the item then the column width.

format()没有这样的功能:

print "1234567890" * 2
print "{:4}{:4}{:4}{:4}".format('aaaa', 'bbbb', 'cccc', 'dddd')

 output: 
12345678901234567890
aaaabbbbccccdddd

输出的总宽度为16=4 x 4。在

应明确指定对齐方式:

^{pr2}$

医生说:

'<'   Forces the field to be left-aligned within the available space 
      (this is the default for most objects).

“大多数对象”的语言是我认为你可能会抵触的。字符串、数字等有一个__format__()方法,当您对它们调用format()方法时,当要求它们显示自己时,将调用该方法。看看这个:

print "{:4}".format("a")
print "{:4}".format(9)

 output: 
a   
   9

字符串和数字的对齐方式有不同的默认值。所以我不会依赖于默认值是显式的,然后您就会知道输出是如何合理的。在

说到这里,我必须用17表示最小场宽,才能得到10:

import Tkinter as tk

root = tk.Tk()
root.geometry("1000x200")

lb = tk.Listbox(root, width=150)
lb.insert("1", "{:4}{:4}".format("a", "b") )
lb.insert(tk.END, "1234567890" * 4)
lb.insert(tk.END, "{:<17}{:<10}".format(100, 200) )
lb.pack()

root.mainloop()

有了这个代码,我看到200从第11列开始。好吧,这个对齐问题与tkinter使用的默认字体不是固定宽度有关,也就是说,所有字符占用的空间都不相同。如果要对齐列,则需要使用固定宽度的字体。试试这样的方法:

import Tkinter as tk
import tkFont

root = tk.Tk()

my_font = tkFont.Font(family="Monaco", size=12)  #Must come after the previous line.

root.geometry("1000x200")

lb = tk.Listbox(root, width=150, font=my_font)
lb.insert("1", "{:4}{:4}".format("a", "b") )
lb.insert(tk.END, "1234567890" * 4)
lb.insert(tk.END, "{:>10}{:>10}".format(100, 200) )
lb.pack()

root.mainloop()

相关问题 更多 >

    热门问题