我正在构建,在文本小部件中使用 Tkinter 的收据,它在 GUI 中格式正确
但是当我保存它时,它变成了这样
文本文件乱七八糟
如何在文本文件中获得类似于 GUI 中的文本格式的文本???这是我的代码。
from tkinter import *
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import askyesno
# ------------
app = Tk()
# =================== frames ========================
frame1 = Frame(app)
frame1.pack(side=TOP)
# ----
title_label = Label(frame1, text="Facture", font=("courier", 40, 'bold'))
title_label.pack()
# ----
frame2 = Frame(app, bd=5)
frame2.pack(side=TOP)
# ----
frame3 = Frame(app)
frame3.pack(side=TOP)
# ============================================
# ======--- text field -----======
text_input = Text(frame2, width=47, height=25, bg="aliceblue", fg='black', font=("arial", 14, 'bold'))
text_input.pack()
# ============ in text field ===============
text_input.insert(END, f'--------------------------------- Facture ---------------------------------\n')
text_input.insert(END, f"\nQty " + f"Product" + f" PU" + f" PV/TVAC" + f'\n')
text_input.insert(END, f"\n1 " + f"FANTA CITRON" + f" 2500" + f" 2500")
text_input.insert(END, f"\n1 " + f"BUFFET PER HEAD" + f" 10000" + f" 10000")
text_input.insert(END, f"\n1 " + f"MUKEKE GRILLE OIGNONS" + f"16000" + f" 16000" + f'\n')
text_input.insert(END, f"\nTOTAL" + f" 28500")
# --------- functions ---------
def save():
filepath = asksaveasfilename(
defaultextension = "csv",
filetypes = [("Text Files", "*.csv"), ("All Files", "*.*")])
if not filepath:
return
with open(filepath, 'w') as output_file:
text = text_input.get('1.0', END)
output_file.write(text)
def printR():
pass
def delete():
text_input.delete('1.0', END)
def exit():
iExit = askyesno("Attention", "You are on your way to quit\nAre you sure you want quit")
if iExit > 0:
app.destroy()
# ----------------------------------
# ============---------------===============
# =====--------- Buttons -----------========
save_button = Button(frame3, text="Save", height=3, width=10, command=save)
save_button.grid(row=0, column=0, padx=2)
# ----------------
print_button = Button(frame3, text="Print", height=3, width=10, command=printR)
print_button.grid(row=0, column=1, padx=2)
# ----------------
delete_button = Button(frame3, text="Delete", height=3, width=10, command=delete)
delete_button.grid(row=0, column=2, padx=2)
# ----------------
quit_button = Button(frame3, text="Exit", height=3, width=10, command=exit)
quit_button.grid(row=0, column=3, padx=2)
# ============================================
app.mainloop()
…………………………………………………………………………………………………………………… ……………………………………………………………………………………………………………………