Computer >> Computer tutorials >  >> Programming >> Python

How to save the contents of a Textbox in Tkinter?


To save the contents of a Textbox in Tkinter, we can take the following steps −

  • Create an instance of tkinter frame.

  • Set the size of the frame using win.geometry method.

  • Define a user-defined method "open_text" to open a text file in "read" mode. Read the contents of the text file and save it in a variable called "content". Then, use the "insert" method to insert the contentin a Textbox.

  • Next, define another user-defined method called "save_text" and in it, use the "write" method to save the contents of the textbox in the text file.

  • Create a text widget using the Text method with specified height and width.

  • Create a button to call the open_text method.

  • Create a button to call the open_text method.

  • Finally, run the mainloop of the application window.

Example

# Import tkinter library
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x250")

def open_text():
   text_file = open("test.txt", "r")
   content = text_file.read()
   my_text_box.insert(END, content)
   text_file.close()

def save_text():
   text_file = open("test.txt", "w")
   text_file.write(my_text_box.get(1.0, END))
   text_file.close()

# Creating a text box widget
my_text_box = Text(win, height=10, width=40)
my_text_box.pack()

open_btn = Button(win, text="Open Text File", command=open_text)
open_btn.pack()

# Create a button to save the text
save = Button(win, text="Save File", command=save_text)
save.pack()

win.mainloop()

Output

When you execute the code, it will show the following screen −

How to save the contents of a Textbox in Tkinter?

Now, click the "Open Text File" button to open the text file "test.txt". It will display the contents of the file in the Textbox.

How to save the contents of a Textbox in Tkinter?

Next, type a new line inside the Textbox and click "Save File" to save the contents in "test.txt".

How to save the contents of a Textbox in Tkinter?