Every time I save a new matter number from the tkinter textbox to the txt file, it replaces the previous one. I need it to save on the next line. Below is the code I've tried. Please assist. Thanks and All the best.
from tkinter import *
window = Tk()
window.geometry("700x250")
def save_text():
text_file = open("matters.txt", "w")
text_file.write(my_text_box.get(1.0, END))
text_file.close()
label = Label(window, text = 'Save the matter number 👉 Matter number:').grid(row=3, column=1,)
my_text_box = Text(window, height=2, width=40).grid(row=3, column=2, padx=10, pady=12)
save = Button(window, text="Save matter", command=save_text).grid(row=3, column=3, padx=10, pady=10)
window.mainloop()
You need to open the file in "append" mode 'a'
instead of "write" mode 'w'
if you want to add content to an existing file. Try this instead:
def save_text():
with open('matters.txt', 'a') as text_file: # 'a' specifies 'append' mode
text_file.write(my_text_box.get(1.0, END))
I've used a context manager here (the with
statement) to make opening and closing the file a little cleaner as well