2

我的代码是一个 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 框架中一无所获。我需要探索的唯一选择是首先将所有这些数据写入画布并对齐它们,然后打印画布本身而不是这个文本文件。

对最快的前进方式有任何帮助吗?如果画布是我唯一的选择,请提供使用画布完成这项工作的最简单方法的示例/指针。

4

1 回答 1

0

不是真正的 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

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

于 2018-05-14T10:31:09.687 回答