How do i save what i write in here to a json file?

import tkinter as tk

root = tk.Tk()
root.geometry("1000x750")
root.resizable(False, False)
root.title("My Notes")

my_text = tk.Text(root, font=('Arial', 18), width=100, height=75)
my_text.pack()

root.mainloop()

You can get the text from the widget with the my_text.get method.

If you want all of the text, give the start index as '1.0' (line 1, column 0) and the end index as 'end'.

Note that after root.mainloop() returns, the widget won’t exist any longer, so here I’m getting it when the window closes:

import tkinter as tk

root = tk.Tk()
root.geometry("1000x750")
root.resizable(False, False)
root.title("My Notes")

my_text = tk.Text(root, font=('Arial', 18), width=100, height=75)
my_text.pack()

def on_close():
    print(my_text.get('1.0', 'end'))
    root.destroy()

root.protocol('WM_DELETE_WINDOW', on_close)
root.mainloop()
1 Like

You can use the json module’s dump() function to write out the text to a JSON file. I had ChatGPT write out the code (though it took several iterations to get right and I needed to add a Save button and a confirmation message box. Also it can only save to notes.json but you can edit this if needed.):

import tkinter as tk
import json
from tkinter import messagebox

def save_to_json():
    text_content = my_text.get("1.0", tk.END).strip()  # Get text from the widget
    data = {"notes": text_content}  # Store in a dictionary

    with open("notes.json", "w", encoding="utf-8") as file:
        json.dump(data, file, indent=4)  # Save as JSON

    # Show a message box confirming save
    messagebox.showinfo("Save Successful", "File saved as notes.json")

# Create main window
root = tk.Tk()
root.geometry("1000x750")
root.resizable(False, False)
root.title("My Notes")

# Create a frame to organize widgets
frame = tk.Frame(root)
frame.pack(fill="both", expand=True)

# Create text area
my_text = tk.Text(frame, font=('Arial', 18))
my_text.pack(fill="both", expand=True, side="top")

# Save button (placed at the bottom)
save_button = tk.Button(root, text="Save", font=("Arial", 14), command=save_to_json)
save_button.pack(side="bottom", pady=10)  # Ensure it appears at the bottom

root.mainloop()
1 Like