写入文件时如何对齐或对齐行和列?



我的代码是一个Tkinter应用程序,用于创建账单并打印它。

创建帐单时,值将写入文本文件。但是,输出没有正确对齐,有没有办法指定一个带有固定参数的模板作为每行的位置?

这是一个最小的程序:

#This is a working python script
#Declare and assign field names
vbill_SubTotal = "Sub Total:        Rs. "
vbill_TaxTotal = "Tax Total:        Rs. "
vbill_RoundOff = "Round Off:        Rs. "
vbill_GrandTotal = "Grand Total:      Rs. "
#Declare the variables and assign values
vsubTotal = 20259.59
vtaxTotal = 5097.78
vroundOff = 0.27
vgrandTotal = 25358.00
#Concatenate all values into one variable
vbill_contents = vbill_SubTotal + str(vsubTotal) + 'n' +
vbill_TaxTotal + str(vtaxTotal)  + 'n' +
vbill_RoundOff + str(vroundOff) + 'n'+
vbill_GrandTotal + (str(vgrandTotal)) + 'n'
#Create a new bill
mybill = "bill.txt"
writebill = open(mybill,"w")
#Write the contents into the bill
writebill.write(vbill_contents)

执行此程序时,输出将写入相对路径中的记事本文件"bill.txt"。文件中的数据如下:

Sub Total:        Rs. 20259.59
Tax Total:        Rs. 5097.78
Round Off:        Rs. 0.27
Grand Total:      Rs. 25358.00

输出乍一看很整洁,但仔细观察时没有定义对齐方式。这是我想要的输出,所有小数点都应该在一列中:

Sub Total:        Rs. 20259.59
Tax Total:        Rs.  5097.78
Round Off:        Rs.     0.27
Grand Total:      Rs. 25358.00

我已经为此研究了很多教程,但在 Tkinter 框架中找不到任何东西。我需要探索的唯一选择是先将所有这些数据写入画布并对齐它们,然后打印画布本身而不是此文本文件。

对最快的前进方向有什么帮助吗?如果 canvas 是我唯一的选择,请提供一个示例/指针,说明使用 canvas 来完成这项工作的最简单方法。

不是真正的 tkinter 函数,只是字符串格式之一。

python 字符串库允许您定义输出字符串的格式,它允许填充、左右对齐等。

举个例子

name = "Sub Total"
price = 20789.95
line_format = "{field_name: <18s}Rs. {price:>10.2f}"
print(line_format.format(field_name=name,price=price))

将输出

Sub Total         Rs.   20789.95

line_format变量包含格式规范的"模板"。您可以在大括号 {} 内指定每个"字段"。

{field_name: <18s}
field_name - The name of the dictionary field to format here
' ' a space - Pad with spaces - this is the default
< - Left align - this is default too
18 - Pad the field to fill 18 characters
s - input is a string
{price:>10.2f}
price - the name of the dictionary field to format here
> - Right Align
10 - Pad to ten characters
2 - 2 decimal places
f - input is a floating point number

格式化字符串后,您可以将其写入画布或您希望显示它的其他位置。

最新更新