简体   繁体   English

tkinter Text 小部件中的列宽是否可变?

[英]Are column widths variable in tkinter Text widgets?

I'm trying to display a bill in a tkinter Text box, but I can't get all the columns (like name, price, etc.) to align.我正在尝试在 tkinter Text框中显示帐单,但无法对齐所有列(如名称、价格等)。 Is it because some letters are wider than others?是因为有些字母比其他字母宽吗?

ct=5.0
for i in lst_bill:
    txt_bill.insert(ct,'\n' + str(int(ct-4)))  # for sl.no
    txt_bill.insert(tk.END,' '*11+i[0])
    txt_bill.insert(tk.END,' '*(40-len(i[0]))+str(i[1]))
    txt_bill.insert(tk.END,' '*(10-len(str(i[1]))) +i[2])
    ct+=1

lst_bill looks something like this: lst_bill看起来像这样:

[['Orange Cake', 20, 'milk'], ['Red Velvet Cake', 30, 'None'], 
 ['BlackCoffee', 5, 'None'], ['Pumpkin Pie', 10, 'Milk']]

Screenshot of current results当前结果的屏幕截图

Yes, it is because you are using a variable-width font.是的,这是因为您使用的是可变宽度字体。

You can use tab stops instead of padding the data with spaces.您可以使用制表位而不是用​​空格填充数据。 For example, to set the tab stops at 50 pixels, 200 pixels, and then 250 pixels, and with the third column being right-justified you can do it like this:例如,要将制表位设置为 50 像素、200 像素和 250 像素,并且第三列右对齐,您可以这样做:

txt_bill.configure(tabs="50 200 right 250")
ct=5.0
for i in lst_bill:
    txt_bill.insert("end", f"{int(ct-4)}\t{i[0]}\t{i[1]}\t{i[2]}\n")
    ct += 1

截屏

You might want to compute the widths based on the font and the maximum width of the data in each column, but this gives the general idea.您可能希望根据每列中数据的字体和最大宽度来计算宽度,但这给出了总体思路。

The canonical description of how to define tabstops is in the tcl/tk documentation for the text widget.如何定义制表位的规范描述在文本小部件的tcl/tk 文档中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM