I'm trying to transfer the content of a window onto an external file but when I do, it shows incomplete amount of items. How do I make it so that the rec_content shows everything?
Code:
get_content = listbox2.get(0, END) # Get the items selected by user
bb = Label(receipt_window, text="Bert's Burgers")
line1 = Label(receipt_window, text='----------------------------------------------------------------')
bb.pack()
line1.pack()
for con_item in get_content: # Split the item into two variables to format text
con1, con2 = con_item.split('PHP')
rec_content = f'{con1:<30}costs PHP{con2:<8}'
receipt = Label(receipt_window, text=rec_content)
receipt.pack()
item_list = [str(rec_content), "Cost" str(cost), "Cash Paid" payment.get(), "Change" str(change_formula)]
with open("receipt.txt", "w") as f:
for line in item_list:
f.write(line)
f.write("\n")
CodePudding user response:
A very easy and convenient way to format text is to use a triple quote string.
This enables you to quickly organise or modify your receipt.
Here is a demonstration.
con1 = 1
con2 = 130
con3 = 2
con4 = 100
con5 = 3
con6 = 75
cost = con2 con4 con6
payment = 310
change = payment - cost
receipt = f"""
Bert's Burgers
{con1} pc(s) Vegan Burger costs PHP {con2}
{con3} pc(s) Big Fries costs PHP {con4}
{con5} pc(s) French Fries costs PHP {con6}
----------------------------------------------------------------
Total Cost: PHP {cost}
Cash Tendered: PHP {payment}
Change: PHP {change}
"""
with open("receipt.txt", "wt") as f:
f.write(receipt)
with open("receipt.txt", "rt") as f:
receipt = f.read()
print(receipt)
CodePudding user response:
You have the similar issue as in your last question: You have used same variable rec_content
in the for loop, then add this variable into item_list
outside the for loop. So item_list
will have the last item in the for loop.
You need to append rec_content
into item_list
in the for loop:
item_list = []
for con_item in get_content:
con1, con2 = con_item.split('PHP')
rec_content = f'{con1:<30}costs PHP{con2:<8}'
receipt = Label(receipt_window, text=rec_content)
receipt.pack()
item_list.append(rec_content)
item_list = [f'Cost {cost}',
f'Cash Paid {payment.get()}',
f'Change {change_formula}']
with open('receipt.txt', 'w') as f:
f.write('\n'.join(item_list))